Recursion. Is it corect do like this?

Advertisements
def slice_num(num, lst=None):
    if lst is None:
        lst = []
    if num > 0:
        lst.append(num % 10)
        slice_num(num//10, lst)
    return lst[::-1]


print(slice_num(564))

Need use recurcion. Is it corect choice to make a list digits from number?

>Solution :

If you still insist in using recursion despite the suggestion given from the comments here is a simple approach:

def slice_num(num):
    if num < 0:
        num = -num
    if num == 0:
        return []
    else:
        return slice_num(num // 10) + [num % 10]

print(slice_num(564))

Output:

[5, 6, 4]

Leave a Reply Cancel reply