Home > Mobile >  Python while loop extra iterations?
Python while loop extra iterations?

Time:04-12

While the code works as intended, it's repeating more than it needs to, and I can't figure out why. I've included debug lines so I can see every step of the process, and even though the variable 'num' is updated at the end of each iteration, once the length of num reaches 0, it doesn't stop immediately. What am I missing?

Here is my input code:

def MathChallenge(num):
  count = 0

  #check for win
  while len(str(num)) > 1:
    # multiply function
    count  =1
    #print('count increased') #debug
    #print('input num') #debug
    #print num #debug
    num = list(str(num))
    #print('breaking down') #debug 
    #print (num) #debug
    #print ('starting multiply') #debug
    total = 1
    for i in num:
      total *= int(i)
    #  print(total) #debug
    num = int(total)
    #print ('ending multiply') #debug
    #print num #debug
    if len(str(num)) == 1:
      break
    MathChallenge(num)

  return count
# keep this function call here 
print MathChallenge(raw_input())

Here is my output:

count increased
input num
9999
breaking down
['9', '9', '9', '9']
starting multiply
9
81
729
6561
ending multiply
6561
count increased
input num
6561
breaking down
['6', '5', '6', '1']
starting multiply
6
30
180
180
ending multiply
180
count increased
input num
180
breaking down
['1', '8', '0']
starting multiply
1
8
0
ending multiply
0
count increased
input num
180
breaking down
['1', '8', '0']
starting multiply
1
8
0
ending multiply
0
count increased
input num
6561
breaking down
['6', '5', '6', '1']
starting multiply
6
30
180
180
ending multiply
180
count increased
input num
180
breaking down
['1', '8', '0']
starting multiply
1
8
0
ending multiply
0
count increased
input num
180
breaking down
['1', '8', '0']
starting multiply
1
8
0
ending multiply
0
3

CodePudding user response:

Now it's clear - return keyword returns from one call of MathChallenge. What are you doing is looping over digits in while loop and for every iteration you run MathChallenge. Every new call will run the same loop. Look at this snippet:

def foo(i):
    print(i, end=" ")
    for _ in range(i):
        foo(i - 1)
    return
      
print(foo(3)) # 3 2 1 0 1 0 2 1 0 1 0 2 1 0 1 0 hell lot numbers!

You should decide for iterative approach (just erase calling of MathChallenge) or recursive approach:

import math


def MathChallenge(num, count):
    if num < 10:
        return count
    digits = (int(d) for d in str(num))
    # python3
    # return MathChallenge(math.prod(digits), count   1)
    # python2
    return MathChallenge(reduce(lambda x, y: x * y, digits, 1), count   1)



print(MathChallenge(9999, 0))
  • Related