'Learning Recursive functions and my return won't hit when criteria is met [duplicate]
I'm working through an algorithm and wanted to try to use recursive functions to solve it. In doing so I have this code:
def persistence(n, count=0):
holder = 1
if n < 9:
return count
num = [int(a) for a in str(n)]
print(f'num {num}')
for i in num:
holder = holder * i
print(f'holder {holder}')
count += 1
print(f'count {count}')
if holder < 9:
print(f'The final count is {count}')
return count
else:
persistence(holder, count)
persistence(39)
The problem is the return in the If statement never gets called when the criteria is met:
if holder < 9:
print(f'The final count is {count}')
return count
else:
persistence(holder, count)
It will run the print but never run the return and instead recalls the functions until nothing is returned.
Solution 1:[1]
I think you just need to return the result of the recursive call in the final line of the function persistence():
def persistence(n, count=0):
holder = 1
if n < 9:
return count
num = [int(a) for a in str(n)]
print(f'num {num}')
for i in num:
holder = holder * i
print(f'holder {holder}')
count += 1
print(f'count {count}')
if holder < 9:
print(f'The final count is {count}')
return count
else:
return persistence(holder, count)
persistence(39)
Output:
num [3, 9]
holder 3
holder 27
count 1
num [2, 7]
holder 2
holder 14
count 2
num [1, 4]
holder 1
holder 4
count 3
The final count is 3
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | constantstranger |
