I'm having this extremely strange problem and I guess it's something simple but it just makes no sense to me.
CodeWars question states:
Define a function that takes a multi digit number and multiplies each digit until you get a single digit answer, so for example
persistence(39)
would compute3*9 = 27, 2*7 = 14, 1*4 = 4, return 4
I wanted to try and solve this recursively, and I have the answer, but the program will never break out of the function. I've stepped through this program multiple times and it gets to the return statement and then jumps back up into the if
statement and calls persistence
again.
Code below:
def persistence(n):
arg_to_list = list(str(n))
# If the argument is > one digit
if len(arg_to_list) > 1:
total = int(arg_to_list[0])
for digit in arg_to_list[1:]:
# Don't want any muplication by 0
if digit != "0":
total *= int(digit)
# Call the function again on the total
persistence(total)
else:
return n