ascentman ascentman - 26 days ago 16
Python Question

python: recursive function counter. persistence issue

Maybe some of you already tried to resolve "persistent bugger" task on codewars.
So here is my turn:)

def persistence(num):
multi = 1
while num:
multi *= num % 10
num /= 10
global count
count += 1
if(multi >= 10):
persistence(multi)
else:
return 0
return count
count = 0
print(persistence(39))
#print(persistence(25))


It gives me correct iteration results and successful result of 1 try.
(persistence(39) => 3 # Because 3*9 = 27, 2*7 = 14, 1*4=4)
But because of using global variable I can't run it's more than 1 time. How to deal with this? How can I create counter and at this time use this function recursively?

Answer

In recursion, if you need to manage state, you manage it within the arguments of the function:

def persistence(num):
  #here is your code, slightly modified.
  def _persist(num,count=0):
    multi = 1
    while num:
      multi *= num % 10
      num /= 10
    if(multi >= 10):
      return _persist(multi,count+1)
    else:
      return count
  return _persist(num)

where you're effectively presenting one interface for your function but you're really calling it recursively via _perist.

Comments