sneakysnake sneakysnake - 3 years ago 62
Python Question

How to Get My Recursive Function to Return 0 in Python

For my recursion assignment, the only built in function we are allowed to use is

len()
and 'print()'. So, not even
int()
is allowed to be used. The function I am supposed to make is supposed to break apart a number and print out each digit in the number.
So,

>>breakApart(757890)

7
5
7
8
9
0


This is what I have come up with so far,

def breakApart(number):
c=0
while number//10**c>=10:
c+=1
integer_part=((number-(number%10**c))//(10**c))
if number//10**c==0:
return
elif number//10**c>0:
print(integer_part)
return breakApart(number%10**c)


This works for all numbers, except it will not print out 0s. I was thinking of writing something along the lines of,

if (number%10**c)>+10 and (number%10**c)//(10**(c-1))<1:
print(0)
return breakApart(number%10**c)


But if there are consecutive 0s, it will not print all of them. I guess I could use another counter like I did at the beginning, but if anyone could think of less convoluted ways for me to approach this, please let me know.

Answer Source

Use recursion to your advantage here, making the print call come after your recursive call:

In [1]: def tell_digits(n):
   ...:     rest, first = n // 10, n % 10
   ...:     if rest:
   ...:         tell_digits(rest)
   ...:     print(first)
   ...:

In [2]: tell_digits(757890)
7
5
7
8
9
0

Note what happens if I put the print call before the recursive call:

In [3]: def tell_digits(n):
   ...:     rest, first = n // 10, n % 10
   ...:     print(first)
   ...:     if rest:
   ...:         tell_digits(rest)
   ...:

In [4]: tell_digits(757890)
0
9
8
7
5
7
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download