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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
To return a value, you need to use return instead of print.
But also pay attention to this:
- When using
returnyou 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. whenn < 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))
Method 2
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0