Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursion. Is it corect do like this?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading