forked from AllenDowney/ThinkPython2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathunstable_sort.py
71 lines (48 loc) · 1.54 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
68
69
70
71
"""This module contains a code example related to
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
Copyright 2015 Allen Downey
License: http://creativecommons.org/licenses/by/4.0/
"""
from __future__ import print_function, division
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)