X Tutup
Skip to content

Commit eb4112c

Browse files
committed
Updating code
1 parent 4d2d470 commit eb4112c

File tree

13 files changed

+114090
-99254
lines changed

13 files changed

+114090
-99254
lines changed

code/birthday.py

Lines changed: 48 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,77 @@
1-
"""This module contains code from
2-
Think Python by Allen B. Downey
3-
http://thinkpython.com
1+
"""This module contains a code example related to
42
5-
Copyright 2012 Allen B. Downey
6-
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
3+
Think Python, 2nd Edition
4+
by Allen Downey
5+
http://thinkpython2.com
76
7+
Copyright 2015 Allen Downey
8+
9+
License: http://creativecommons.org/licenses/by/4.0/
810
"""
911

12+
from __future__ import print_function, division
13+
1014
import random
1115

16+
1217
def has_duplicates(t):
13-
"""Returns True if any element appears more than once in (t),
14-
False otherwise."""
18+
"""Returns True if any element appears more than once in a sequence.
19+
20+
t: list
21+
22+
returns: bool
23+
"""
24+
# make a copy of t to avoid modifying the parameter
1525
s = t[:]
1626
s.sort()
27+
28+
# check for adjacent elements that are equal
1729
for i in range(len(s)-1):
1830
if s[i] == s[i+1]:
1931
return True
2032
return False
2133

2234

2335
def random_bdays(n):
24-
"""Returns a list of integers between 1 and 365, with length (n)."""
36+
"""Returns a list of integers between 1 and 365, with length n.
37+
38+
n: int
39+
40+
returns: list of int
41+
"""
2542
t = []
2643
for i in range(n):
2744
bday = random.randint(1, 365)
2845
t.append(bday)
2946
return t
3047

3148

32-
def count_matches(students, samples):
33-
"""Generates (samples) samples of (students) students, and counts
34-
how many of them have at least one pair of students with the same bday."""
49+
def count_matches(num_students, num_simulations):
50+
"""Generates a sample of birthdays and counts duplicates.
51+
52+
num_students: how many students in the group
53+
num_samples: how many groups to simulate
54+
55+
returns: int
56+
"""
3557
count = 0
36-
for i in range(samples):
37-
t = random_bdays(students)
58+
for i in range(num_simulations):
59+
t = random_bdays(num_students)
3860
if has_duplicates(t):
3961
count += 1
4062
return count
4163

42-
"""run the birthday simulation 1000 times and print the number of matches"""
43-
num_students = 23
44-
num_simulations = 1000
45-
count = count_matches(num_students, num_simulations)
4664

47-
print 'After %d simulations' % num_simulations
48-
print 'with %d students' % num_students
49-
print 'there were %d simulations with at least one match' % count
65+
def main():
66+
"""Runs the birthday simulation and prints the number of matches."""
67+
num_students = 23
68+
num_simulations = 1000
69+
count = count_matches(num_students, num_simulations)
70+
71+
print('After %d simulations' % num_simulations)
72+
print('with %d students' % num_students)
73+
print('there were %d simulations with at least one match' % count)
74+
75+
76+
if __name__ == '__main__':
77+
main()

code/find_duplicates.py

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
1-
"""This module contains code from
2-
Think Python by Allen B. Downey
3-
http://thinkpython.com
1+
"""This module contains a code example related to
42
5-
Copyright 2012 Allen B. Downey
6-
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
3+
Think Python, 2nd Edition
4+
by Allen Downey
5+
http://thinkpython2.com
76
7+
Copyright 2015 Allen Downey
8+
9+
License: http://creativecommons.org/licenses/by/4.0/
810
"""
911

12+
from __future__ import print_function, division
13+
1014
import os
1115

16+
1217
def walk(dirname):
1318
"""Finds the names of all files in dirname and its subdirectories.
1419
@@ -50,6 +55,12 @@ def pipe(cmd):
5055
5156
Returns (res, stat), the output of the subprocess and the exit status.
5257
"""
58+
# Note: os.popen is deprecated
59+
# now, which means we are supposed to stop using it and start using
60+
# the subprocess module. But for simple cases, I find
61+
# subprocess more complicated than necessary. So I am going
62+
# to keep using os.popen until they take it away.
63+
5364
fp = os.popen(cmd)
5465
res = fp.read()
5566
stat = fp.close()
@@ -105,12 +116,12 @@ def print_duplicates(d):
105116
"""
106117
for key, names in d.iteritems():
107118
if len(names) > 1:
108-
print 'The following files have the same checksum:'
119+
print('The following files have the same checksum:')
109120
for name in names:
110-
print name
121+
print(name)
111122

112123
if check_pairs(names):
113-
print 'And they are identical.'
124+
print('And they are identical.')
114125

115126

116127
if __name__ == '__main__':

code/find_duplicates_copy.py

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
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+
import os
15+
16+
17+
def walk(dirname):
18+
"""Finds the names of all files in dirname and its subdirectories.
19+
20+
dirname: string name of directory
21+
"""
22+
names = []
23+
for name in os.listdir(dirname):
24+
path = os.path.join(dirname, name)
25+
26+
if os.path.isfile(path):
27+
names.append(path)
28+
else:
29+
names.extend(walk(path))
30+
return names
31+
32+
33+
def compute_checksum(filename):
34+
"""Computes the MD5 checksum of the contents of a file.
35+
36+
filename: string
37+
"""
38+
cmd = 'md5sum ' + filename
39+
return pipe(cmd)
40+
41+
42+
def check_diff(name1, name2):
43+
"""Computes the difference between the contents of two files.
44+
45+
name1, name2: string filenames
46+
"""
47+
cmd = 'diff %s %s' % (name1, name2)
48+
return pipe(cmd)
49+
50+
51+
def pipe(cmd):
52+
"""Runs a command in a subprocess.
53+
54+
cmd: string Unix command
55+
56+
Returns (res, stat), the output of the subprocess and the exit status.
57+
"""
58+
# Note: os.popen is deprecated
59+
# now, which means we are supposed to stop using it and start using
60+
# the subprocess module. But for simple cases, I find
61+
# subprocess more complicated than necessary. So I am going
62+
# to keep using os.popen until they take it away.
63+
64+
fp = os.popen(cmd)
65+
res = fp.read()
66+
stat = fp.close()
67+
assert stat is None
68+
return res, stat
69+
70+
71+
def compute_checksums(dirname, suffix):
72+
"""Computes checksums for all files with the given suffix.
73+
74+
dirname: string name of directory to search
75+
suffix: string suffix to match
76+
77+
Returns: map from checksum to list of files with that checksum
78+
"""
79+
names = walk(dirname)
80+
81+
d = {}
82+
for name in names:
83+
if name.endswith(suffix):
84+
res, stat = compute_checksum(name)
85+
checksum, _ = res.split()
86+
87+
if checksum in d:
88+
d[checksum].append(name)
89+
else:
90+
d[checksum] = [name]
91+
92+
return d
93+
94+
95+
def check_pairs(names):
96+
"""Checks whether any in a list of files differs from the others.
97+
98+
names: list of string filenames
99+
"""
100+
for name1 in names:
101+
for name2 in names:
102+
if name1 < name2:
103+
res, stat = check_diff(name1, name2)
104+
if res:
105+
return False
106+
return True
107+
108+
109+
def print_duplicates(d):
110+
"""Checks for duplicate files.
111+
112+
Reports any files with the same checksum and checks whether they
113+
are, in fact, identical.
114+
115+
d: map from checksum to list of files with that checksum
116+
"""
117+
for key, names in d.iteritems():
118+
if len(names) > 1:
119+
print('The following files have the same checksum:')
120+
for name in names:
121+
print(name)
122+
123+
if check_pairs(names):
124+
print('And they are identical.')
125+
126+
127+
if __name__ == '__main__':
128+
d = compute_checksums(dirname='.', suffix='.py')
129+
print_duplicates(d)

code/grid.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
1-
"""This module contains code from
2-
Think Python by Allen B. Downey
3-
http://thinkpython.com
1+
"""This module contains a code example related to
42
5-
Copyright 2012 Allen B. Downey
6-
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
3+
Think Python, 2nd Edition
4+
by Allen Downey
5+
http://thinkpython2.com
76
7+
Copyright 2015 Allen Downey
8+
9+
License: http://creativecommons.org/licenses/by/4.0/
810
"""
911

12+
from __future__ import print_function, division
13+
1014
# here is a mostly-straightforward solution to the
1115
# two-by-two version of the grid.
1216

@@ -19,18 +23,18 @@ def do_four(f):
1923
do_twice(f)
2024

2125
def print_beam():
22-
print '+ - - - -',
26+
print('+ - - - -', end=' ')
2327

2428
def print_post():
25-
print '| ',
29+
print('| ', end=' ')
2630

2731
def print_beams():
2832
do_twice(print_beam)
29-
print '+'
33+
print('+')
3034

3135
def print_posts():
3236
do_twice(print_post)
33-
print '|'
37+
print('|')
3438

3539
def print_row():
3640
print_beams()
@@ -52,19 +56,19 @@ def one_four_one(f, g, h):
5256
h()
5357

5458
def print_plus():
55-
print '+',
59+
print('+', end=' ')
5660

5761
def print_dash():
58-
print '-',
62+
print('-', end=' ')
5963

6064
def print_bar():
61-
print '|',
65+
print('|', end=' ')
6266

6367
def print_space():
64-
print ' ',
68+
print(' ', end=' ')
6569

6670
def print_end():
67-
print
71+
print()
6872

6973
def nothing():
7074
"do nothing"
@@ -108,4 +112,4 @@ def print_grid():
108112
--- Allen
109113
"""
110114

111-
print comment
115+
print(comment)

code/has_duplicates.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
1-
"""This module contains code from
2-
Think Python by Allen B. Downey
3-
http://thinkpython.com
1+
"""This module contains a code example related to
42
5-
Copyright 2012 Allen B. Downey
6-
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
3+
Think Python, 2nd Edition
4+
by Allen Downey
5+
http://thinkpython2.com
76
7+
Copyright 2015 Allen Downey
8+
9+
License: http://creativecommons.org/licenses/by/4.0/
810
"""
911

12+
from __future__ import print_function, division
13+
1014

1115
def has_duplicates(t):
1216
"""Checks whether any element appears more than once in a sequence.
@@ -35,12 +39,12 @@ def has_duplicates2(t):
3539

3640
if __name__ == '__main__':
3741
t = [1, 2, 3]
38-
print has_duplicates(t)
42+
print(has_duplicates(t))
3943
t.append(1)
40-
print has_duplicates(t)
44+
print(has_duplicates(t))
4145

4246
t = [1, 2, 3]
43-
print has_duplicates2(t)
47+
print(has_duplicates2(t))
4448
t.append(1)
45-
print has_duplicates2(t)
49+
print(has_duplicates2(t))
4650

0 commit comments

Comments
 (0)
X Tutup