Home > Mobile >  How to *return* Binary of decimal in recursion code Python
How to *return* Binary of decimal in recursion code Python

Time:05-01

Learning Recursion. I was able to write Python code to print binary number using recursion but couldn't figure out how to return this binary number. I am only getting the first mod value when I return, probably because, as I understand, the stack folds back to the beginning by the time it can return. (Hope this is not wrong). I would greatly appreciate if you could not only provide your answer to get the function to return the result but also explain how it works.

def binary(n):

if n == 0:
    return
else:
   binary (n//2)       
   print (n%2,end="")

binary(233)

Thank you

Arun

CodePudding user response:

def binary(n):
    if n == 0:
        return ""
    else:
        i = n % 2
        print(i, end="")
        return binary(n // 2)   str(i)

x = binary(233)
print()  # seperate the print's in binary from this print
print(x)

To actually return something from the function you need to put something into the return statement. Here for each call of binary(n) i'm returning the number obtained by your operation as a string so I can concatenate it together and return it at the end.

CodePudding user response:

To return a value, you need to use return instead of print.

But also pay attention to this:

  • When using return you need to accumulate the binary digits in a string
  • The base case is not correct: 0 does not translate to an empty string when that is the original value of n (then you want to get 0 back). It only should be an empty string if you are in a recursive call. The way to solve this, is to stop the recursion one step earlier, i.e. when n < 2.

Here is how that works out:

def binary(n):
    if n < 2:
        return str(n)
    else:
        return binary(n // 2)   str(n % 2)

Call as:

print(binary(13))
  • Related