-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.py
137 lines (108 loc) · 2.95 KB
/
lib.py
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#!/bin/python3
import math
import sys
def sort_insert(inlist, inelem, sort=None):
# TODO : binatu search
insertflag = False
li = inlist
if sort:
for idx, e in enumerate(li):
if sort(inelem) >= sort(e):
li.insert(idx, inelem)
insertflag = True
break
# catches input that had he least sort value
# acts as default for when no sort is given
if not insertflag:
li.append(inelem)
return li
def bin_sort_rec(inlist, inelem, start, end, sort):
start_e = inlist[start]
end_e = inlist[end]
if end <= start + 1:
if sort(inelem) > sort(start_e):
inlist.insert(start, inelem)
elif sort(inelem) > sort(end_e):
inlist.insert(end, inelem)
else:
inlist.insert(end+1, inelem)
return inlist
inter = end - start
mid = end - inter / 2
mid = math.floor(mid)
pivote = inlist[mid]
try:
if sort(inelem) == sort(pivote):
inlist.insert(mid, inelem)
return inlist
elif sort(inelem) > sort(pivote):
return bin_sort_rec(inlist, inelem, start, mid, sort)
elif sort(inelem) < sort(pivote):
return bin_sort_rec(inlist, inelem, mid, end, sort)
# except Exception as e:
except IOError as e:
print("\ncould not sort")
print(inelem)
print(e)
inlist.append(inelem)
return inlist
def bin_sort_ins(inlist, inelem, sort=None):
if not inlist:
return [inelem]
if not sort:
return inlist.append(inelem)
if sort:
start = 0
end = len(inlist) - 1
return bin_sort_rec(inlist, inelem, start, end, sort)
def quicksort(inlist, func):
if not inlist:
return None
if len(inlist) <= 1:
return inlist
pivot = inlist[0]
large = []
small = []
for x in inlist[1:]:
try:
if func(x) < func(pivot):
large.append(x)
else:
small.append(x)
except TypeError as e:
# if types are unorderable, most often a None field,
# put x in small and let it sink to the bottom
small.append(x)
r_small = quicksort(small, func)
r_large = quicksort(large, func)
if r_small:
if r_large:
ret = r_small + [pivot] + r_large
else:
ret = r_small + [pivot]
else:
if r_large:
ret = [pivot] + r_large
else:
ret = [pivot]
return ret
def test_sort(e):
li = [1, 2, 3, 4, 5, 6, 7, 8]
li.reverse()
s = None
s = lambda x: x
ll = bin_sort_ins(li, e, s)
return ll
def test_quick():
li = [1,8,3,4,2,5,9,0]
func = lambda x: x
ll = quicksort(li, func)
print(li)
print(ll)
if __name__ == '__main__':
test_quick()
# for x in range(10):
# try:
# test_sort(x)
# except:
# pass