Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96169
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
15
def most_frequent(s):
16
"""Sorts the letters in s in reverse order of frequency.
17
18
s: string
19
20
Returns: list of letters
21
"""
22
hist = make_histogram(s)
23
24
t = []
25
for x, freq in hist.items():
26
t.append((freq, x))
27
28
t.sort(reverse=True)
29
30
res = []
31
for freq, x in t:
32
res.append(x)
33
34
return res
35
36
37
def make_histogram(s):
38
"""Make a map from letters to number of times they appear in s.
39
40
s: string
41
42
Returns: map from letter to frequency
43
"""
44
hist = {}
45
for x in s:
46
hist[x] = hist.get(x, 0) + 1
47
return hist
48
49
50
def read_file(filename):
51
"""Returns the contents of a file as a string."""
52
return open(filename).read()
53
54
55
if __name__ == '__main__':
56
string = read_file('emma.txt')
57
letter_seq = most_frequent(string)
58
for x in letter_seq:
59
print(x)
60
61