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

How to keep track of the results while doing a recursion

I want to use recursion in converting a decimal number into octal. I have a problem in keeping track of the results of each recursion step and append them into a list or a string. I will appreciate your help.

def dectoOct(decimal):
    L = ''
    if decimal == 0:
        return 0
    if decimal > 0:
       L = str(decimal % 8) + L
       dectoOct(decimal//8)
    return L    
print(dectoOct(30))

>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

You just need to return the value as you go:

def dec_to_oct(n):
    if n == 0:
        return '0'
     
    left = n // 8
    if left:
        return dec_to_oct(n // 8) + str(n % 8)
    else:
        return str(n % 8)

# all are strings
foo(0)  # 0
foo(37) # 45
foo(40) # 50
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