List didn't return at the end of the recursion

Question:

I tried to convert a decimal number to binary using recursion and at the end it is supposed to return the list that is holding the digits of binary number. But instead of returning that list it returns None. But when I tried to print the list in recursive function, it prints the list correctly. Can someone point out what am I doing wrong here?

def binary_rec(n, l=[]):
    if n>=1:
        r = n%2
        l.append(r)
        binary_rec(n//2, l)
    else:
        print(sorted(l,reverse=True))
        l_rev = sorted(l,reverse=True)
        #ll = l.copy()
        #print('I am ll')
        #print(ll)
        #return ll
        return l_rev

if __name__ == '__main__':
    import sys
    inp = sys.argv[1]
    x = binary_rec(int(inp),l=[])
    print(x)

Asked By: tad

||

Answers:

You have to return the list each time you call the function recursively:

def binary_rec(n, l=[]):
    if n>=1:
        r = n%2
        l.append(r)
        return binary_rec(n//2, l)
    else:
        print(sorted(l,reverse=True))
        l_rev = sorted(l,reverse=True)
        #ll = l.copy()
        #print('I am ll')
        #print(ll)
        #return ll
        return l_rev

if __name__ == '__main__':
    import sys
    inp = sys.argv[1]
    x = binary_rec(int(inp),l=[])
    print(x)

When you return the list at the end of the function, the value is received at the last time you called the function. Since you didn’t handle the value as it returned, it disappeared at the very first time the function returned because the previous call was from inside the function. By adding the return you are passing the list to the call before that and so on.

You could also see that if you pass to the func first value 0, it returns an empty list, but not None. So you can infer that the problem is at the recursive call of the function.

Answered By: nokla

You don’t return the result of the recursive call, change to this:

return binary_rec(n//2, l)
Answered By: codingStarter
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.