Created
September 16, 2012 02:04
-
-
Save cnelsonsic/3730747 to your computer and use it in GitHub Desktop.
Sort a file's lines by asking which lines are better than the others.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''A command line utility to sort a list of things. | |
It presents you two options, from which you pick the "best". | |
The list is sorted and presented to you in sorted order. | |
So, given a file with some things in it: | |
$ cat things.txt | |
asdf | |
qwer | |
zxcv | |
And we say qwer is better than asdf, and zxcv is better than qwer... | |
$ python2.7 sort.py things.txt | |
(0):"qwer" OR (1):"asdf"? 0 | |
(0):"zxcv" OR (1):"qwer"? 0 | |
Wrote your sorted list to things.txt.out | |
So zxcv is better than qwer, which is better than asdf. | |
$ cat things.txt.out | |
zxcv | |
qwer | |
asdf | |
''' | |
def ask(first, second): | |
'''Ask the user which choice they prefer.''' | |
choice = None | |
while choice not in ("0", "1"): | |
choice = raw_input('(0):"{0}" OR (1):"{1}"? '.format(first.strip(), second.strip())) | |
if choice == "0": | |
return -1 | |
elif choice == "1": | |
return 1 | |
else: | |
return 0 | |
def humansort(items): | |
'''Sort a list of items by asking the user which is better.''' | |
return sorted(items, cmp=ask) | |
if __name__ == "__main__": | |
import fileinput | |
file_input = list(fileinput.input()) | |
filename = fileinput.filename()+".out" | |
out = humansort(file_input) | |
with open(filename, 'w') as f: | |
for line in out: | |
f.write(line) | |
print("Wrote your sorted list to {0}".format(filename)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment