简体   繁体   中英

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.

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

If number can be a string:

def breakApart(number):
    if len(number) == 0:
        return
    else:
        print(number[0])
        breakApart(number[1:])

Or reverse it:

def breakApart(number):
    if len(number) == 0:
        return
    else:
        breakApart(number[:-1])
        print (number[-1])

Something to keep you up at night:

>>> def breakApart(number):
...     return number > 9 and breakApart(number // 10) or print(number % 10)
... 
>>> breakApart(757890)
7
5
7
8
9
0
>>> 

Python 3 specific, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM