Skip to content

Instantly share code, notes, and snippets.

@hexpunk
Last active March 5, 2022 05:17
Show Gist options
  • Save hexpunk/78a5bf782cdbee54e8c727e6731f51b1 to your computer and use it in GitHub Desktop.
Save hexpunk/78a5bf782cdbee54e8c727e6731f51b1 to your computer and use it in GitHub Desktop.
Sorts a list of strings using a series of interactive prompts
#!/usr/bin/env python3
import argparse
import random
import sys
def eprint(*args, **kwargs):
"""Like print but for stderr"""
print(*args, file=sys.stderr, **kwargs)
def cmp(a, b):
answer = None
while answer not in ["1", "2"]:
eprint(f"1) {a}")
eprint(f"2) {b}")
eprint("\nWho wins? ", end="")
answer = input().strip()
eprint()
if answer == "1":
return -1
else:
return 1
class ManualCompare:
def __init__(self, obj, *_args):
self.obj = obj
def __lt__(self, other):
return cmp(self.obj, other.obj) < 0
def __gt__(self, other):
return cmp(self.obj, other.obj) > 0
def __eq__(_self, _other):
return False
def __le__(self, other):
return cmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return cmp(self.obj, other.obj) >= 0
def __ne__(_self, _other):
return True
def main():
parser = argparse.ArgumentParser(
description="Sorts a list of strings using a series of interactive prompts."
)
parser.add_argument(
"file",
type=argparse.FileType("r"),
help="file to read as input",
metavar="FILE",
)
parser.add_argument(
"-r",
"--randomize",
action="store_true",
help="shuffle the list before sorting",
)
args = parser.parse_args()
contestants = [line.rstrip("\n") for line in args.file]
if len(contestants) < 1:
eprint("No contestants found!")
sys.exit(1)
if args.randomize:
random.shuffle(contestants)
print("\n".join(sorted(contestants, key=ManualCompare)))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment