pythonrecursion

Python Recursion Behavior


I have studied recursion, especially in Python, and think I get it. I have learned this form:

def f_Listsum(numList):
   if len(numList) == 1:
       return numList[0] ## Triggers the unwinding of the recursion stack
   else:
       return numList[0] + f_Listsum(numList[1:]) ## Winds up the recursion stack with a shorter and shorter slice of org. list.   

I get it. The recursive calls sort of "wind" things up, and then a stop or "trigger" causes the recursion to collapse into itself and consume the resulting values.

However I ran into this today:

def f_DecToBinary(v_Num):
    if v_Num > 1:
        f_DecToBinary(v_Num // 2)
    print(v_Num % 2,end = '')  

I wanted to substitute the function's "print" with a return of a string, or even a list of INTs, but I can't get it to work, as I don't understand how this recursion is operating. I see that it calls itself each time, and then initiates a collapse when v_Num == 1 or less, but it collapses to outside the "if" statement and then I get lost. When I try to assemble a STR or LIST from the collapse instead of just printing it, I errors or just the last digit returned.

My questions are: How does f_DecToBinary work/function, and how can I capture the output into a string?

Some examples:

print(f_Listsum([1,3,5,7,9])) ## 25
print()
f_DecToBinary(15) ## 1111

Thanks


Solution

  • def DecToBinary(n):
        if n >= 2:
            return DecToBinary(n // 2) + str(n % 2)
        else:
            return str(n)