Last active
September 2, 2019 03:09
-
-
Save jejones3141/c29f1810ea924a31d93b424da0563630 to your computer and use it in GitHub Desktop.
count iterations/recursive calls to a function that repeatedly evaluates the digit product of a base 10 number representation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import reduce | |
from operator import mul | |
# For DRYness's sake, we'll write digitprod here. We have to rull our own prod, since | |
# Python doesn't have one, but will take Trey Hunner's advice and use operator.mul, which | |
# gives * a name so we can avoid a lambda. | |
def digitprod(n): | |
return reduce(mul, (int(c) for c in str(n)), 1) | |
# Now for the real action. We repeatedly evaluate the "digit product" of the base 10 | |
# representation of a number and want to know how many iterations it takes to get to | |
# converge to a one-digit number. The real goal might well be how to instrument | |
# recursive functions in general--perhaps someone's already done it. We got distracted | |
# and did recursion elimination as well as instrumenting the code. | |
# iterative version | |
def dpreduce(n): | |
count = 0 | |
while n > 9: | |
count += 1 | |
n = digitprod(n) | |
return count | |
# recursive version | |
def dpreduce2(n, count = 0): | |
return count if n < 10 else dpreduce2(digitprod(n), count + 1) | |
# Ultimately, I should instruct myself in the ways of hypothesis and write test code. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment