forked from AllenDowney/ThinkPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unstable_sort.py
67 lines (46 loc) · 1.47 KB
/
unstable_sort.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
"""This module contains code from
Think Python by Allen B. Downey
http://thinkpython.com
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import random
def sort_by_length(words):
"""Sort a list of words in reverse order by length.
This is the version in the book; it is stable in the sense that
words with the same length appear in the same order
words: list of strings
Returns: list of strings
"""
t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = []
for length, word in t:
res.append(word)
return res
def sort_by_length_random(words):
"""Sort a list of words in reverse order by length.
This is the solution to the exercise. It is unstable in the
sense that if two words have the same length, their order in
the output list is random.
It works by extending the list of tuples with a column of
random numbers; when there is a tie in the first column,
the random column determines the output order.
words: list of strings
Returns: list of strings
"""
t = []
for word in words:
t.append((len(word), random.random(), word))
t.sort(reverse=True)
res = []
for length, _, word in t:
res.append(word)
return res
if __name__ == '__main__':
words = ['John', 'Eric', 'Graham', 'Terry', 'Terry', 'Michael']
t = sort_by_length_random(words)
for x in t:
print x