Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96166
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 str_fill(i, n):
16
"""Returns i as a string with at least n digits.
17
18
i: int
19
n: int length
20
21
returns: string
22
"""
23
return str(i).zfill(n)
24
25
26
def are_reversed(i, j):
27
"""Checks if i and j are the reverse of each other.
28
29
i: int
30
j: int
31
32
returns:bool
33
"""
34
return str_fill(i, 2) == str_fill(j, 2)[::-1]
35
36
37
def num_instances(diff, flag=False):
38
"""Counts the number of palindromic ages.
39
40
Returns the number of times the mother and daughter have
41
palindromic ages in their lives, given the difference in age.
42
43
diff: int difference in ages
44
flag: bool, if True, prints the details
45
"""
46
daughter = 0
47
count = 0
48
while True:
49
mother = daughter + diff
50
51
# assuming that mother and daughter don't have the same birthday,
52
# they have two chances per year to have palindromic ages.
53
if are_reversed(daughter, mother) or are_reversed(daughter, mother+1):
54
count = count + 1
55
if flag:
56
print(daughter, mother)
57
if mother > 120:
58
break
59
daughter = daughter + 1
60
return count
61
62
63
def check_diffs():
64
"""Finds age differences that satisfy the problem.
65
66
Enumerates the possible differences in age between mother
67
and daughter, and for each difference, counts the number of times
68
over their lives they will have ages that are the reverse of
69
each other.
70
"""
71
diff = 10
72
while diff < 70:
73
n = num_instances(diff)
74
if n > 0:
75
print(diff, n)
76
diff = diff + 1
77
78
print('diff #instances')
79
check_diffs()
80
81
print()
82
print('daughter mother')
83
num_instances(18, True)
84
85