📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division121314def str_fill(i, n):15"""Returns i as a string with at least n digits.1617i: int18n: int length1920returns: string21"""22return str(i).zfill(n)232425def are_reversed(i, j):26"""Checks if i and j are the reverse of each other.2728i: int29j: int3031returns:bool32"""33return str_fill(i, 2) == str_fill(j, 2)[::-1]343536def num_instances(diff, flag=False):37"""Counts the number of palindromic ages.3839Returns the number of times the mother and daughter have40palindromic ages in their lives, given the difference in age.4142diff: int difference in ages43flag: bool, if True, prints the details44"""45daughter = 046count = 047while True:48mother = daughter + diff4950# assuming that mother and daughter don't have the same birthday,51# they have two chances per year to have palindromic ages.52if are_reversed(daughter, mother) or are_reversed(daughter, mother+1):53count = count + 154if flag:55print(daughter, mother)56if mother > 120:57break58daughter = daughter + 159return count606162def check_diffs():63"""Finds age differences that satisfy the problem.6465Enumerates the possible differences in age between mother66and daughter, and for each difference, counts the number of times67over their lives they will have ages that are the reverse of68each other.69"""70diff = 1071while diff < 70:72n = num_instances(diff)73if n > 0:74print(diff, n)75diff = diff + 17677print('diff #instances')78check_diffs()7980print()81print('daughter mother')82num_instances(18, True)838485