Recursive function that prints the binary representation of the integer
10,542
Solution 1
This will not work as expected, as you have print in two places, you will end up with multiple lines, e.g.:
>>> def binary(n):
... if n < 2:
... print n
... else:
... binary(n / 2)
... print n % 2
...
>>> binary(0)
0
>>> binary(1)
1
>>> binary(3)
1
1
>>> binary(9)
1
0
0
1
>>> binary(10)
1
0
1
0
Other answers use strings, so here's one with lists: :)
>>> def binary(n):
... if n < 2:
... return [n]
... else:
... return binary(n / 2) + [n % 2]
...
>>> binary(0)
[0]
>>> binary(1)
[1]
>>> binary(3)
[1, 1]
>>> binary(9)
[1, 0, 0, 1]
>>> binary(10)
[1, 0, 1, 0]
and if you really want a string, it's as simple as this: :)
>>> ''.join(map(str, binary(10)))
'1010'
Of course, since you've already found out about the function bin, you should probably have done this in the first place:
>>> bin(10)[2:]
'1010'
How this reminds me of this:
Happy coding! :)
Solution 2
def binary(n):
if n < 2:
return n
else:
return str(binary(n / 2)) + str(n % 2)
print binary(9)
It return
s instead of print
s, but usually that's better.
Author by
Admin
Updated on July 27, 2022Comments
-
Admin over 1 year
so i have started the code, and i know that everything after the 'else' is probably wrong:
def binary(n): if n < 2: print (n) else: x = (bin(int(n)//2) print (x)
it should do this recursively:
>>> binary(0) 0 >>> binary(1) 1 >>> binary(3) 11 >>> binary(9) 1001
i do need the function to print the binary representation rather than return.
-
Admin about 12 yearshmm i tried this, but the result i get when i try "binary(3)" is >>> binary(3) 1 'None1'
-
amindfv about 12 years@AngelE: I don't - I get "11"
-
Admin about 12 yearsi figured it out, i was putting print rather than return. But i need this function to print and not return unfortunately :(
-
amindfv about 12 years@AngelE: You can't just say "print binary(3)"?
-
Admin about 12 yearsyou're answer is great! for the first solution that you provided, is there any way to make it print horizontally? i tried "print(n%2, end='') but that did not work.