-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractive_sort.py
More file actions
62 lines (45 loc) · 2.14 KB
/
Copy pathinteractive_sort.py
File metadata and controls
62 lines (45 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class InteractiveSortObject:
"""An object that can be sorted interactively.
This object defines the greater than and less than operations, so it can be used with the normal sort() and sorted()
functions.
"""
yes = ["Y", "y", "Yes", "yes"]
no = ["N", "n", "No", "no"]
def __init__(self, value):
"""Initialise this object.
value -- the actual value of this object.
"""
self.value = value
# comparison methods
def __eq__(self, other):
if not isinstance(other, InteractiveSortObject):
raise TypeError("Cannot compare.")
result = input("Are \"{}\" and \"{}\" equal?\n> ".format(self.value, other.value))
# confirm valid input
while result not in self.yes + self.no:
print("Please answer \"y\" or \"n\".")
result = input("Are \"{}\" and \"{}\" equal?\n> ".format(self.value, other.value))
return result in self.yes
def __lt__(self, other):
if not isinstance(other, InteractiveSortObject):
raise TypeError("Cannot compare.")
result = input("Is \"{}\" less than \"{}\"?\n> ".format(self.value, other.value))
# confirm valid input
while result not in self.yes + self.no:
print("Please answer \"y\" or \"n\".")
result = input("Is \"{}\" less than \"{}\"?\n> ".format(self.value, other.value))
return result in self.yes
def __gt__(self, other):
if not isinstance(other, InteractiveSortObject):
raise TypeError("Cannot compare.")
result = input("Is \"{}\" greater than \"{}\"?\n> ".format(self.value, other.value))
# confirm valid input
while result not in self.yes + self.no:
print("Please answer \"y\" or \"n\".")
result = input("Is \"{}\" greater than \"{}\"?\n> ".format(self.value, other.value))
return result in self.yes
def interactive_sort(a):
# turn all into InteractiveSortObjects
b = list(map(lambda obj: InteractiveSortObject(obj), a))
b.sort()
return list(map(lambda obj: obj.value, b))