Human-comparison sort in Python

I recently had a need to sort a large list of items (I admit freely that this list comprised episodes of Battlestar Galactica) by a subjective criterion (my liking). This turned into a minor interface problem; how best to sort these without a) a Netflix queue interface or b) dragging Excel rows around? Also, how could I implement an efficient sorting algorithm, rather than waste time with the simplest bubble sort?

The solution I came up with was almost too simple to feel proud of. Python uses an adaptive mergesort by default, which was plenty good enough for my purposes. All I had to do, then, was have it ask a human to compare each pair of elements.


QUESTION_TEMPLATE = """
1. %s or
2. %s or
3. neither? [neither] """

def human_cmp(a, b):
answer = raw_input(
QUESTION_TEMPLATE % (a, b))
if answer=="1": return -1
elif answer=="2": return 1
else: return 0

EPISODES = open('bsg_episodes.txt').readlines()
EPISODES.sort(human_cmp)
for i, title in EPISODES:
print '%s. %s' % (i, title)

So it just uses the built-in algorithm and asks you for each comparison. Let me tell you, way better than creating a single-elimination tournament bracket in Excel.

1 comments

Post a Comment