forked from AllenDowney/ThinkPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
most_frequent.py
57 lines (38 loc) · 1018 Bytes
/
most_frequent.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
"""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 most_frequent(s):
"""Sorts the letters in s in reverse order of frequency.
s: string
Returns: list of letters
"""
hist = make_histogram(s)
t = []
for x, freq in hist.iteritems():
t.append((freq, x))
t.sort(reverse=True)
res = []
for freq, x in t:
res.append(x)
return res
def make_histogram(s):
"""Make a map from letters to number of times they appear in s.
s: string
Returns: map from letter to frequency
"""
hist = {}
for x in s:
hist[x] = hist.get(x, 0) + 1
return hist
def read_file(filename):
"""Returns the contents of a file as a string."""
return open(filename).read()
if __name__ == '__main__':
s = read_file('words.txt')
t = most_frequent(s)
for x in t:
print x