2

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.

2
  • why don't you use bin if using python: In [1]: bin(9) Out[1]: '0b1001' Commented Feb 21, 2012 at 4:22
  • @Ignacio built-in bin function using his binary function and we have a mutual one? Commented Feb 21, 2012 at 4:23

3 Answers 3

3

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! :)

Sign up to request clarification or add additional context in comments.

1 Comment

you'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.
2
def binary(n):
    if n < 2:
        return n
    else:
        return str(binary(n / 2)) + str(n % 2)


print binary(9)

It returns instead of prints, but usually that's better.

4 Comments

hmm i tried this, but the result i get when i try "binary(3)" is >>> binary(3) 1 'None1'
@AngelE: I don't - I get "11"
i figured it out, i was putting print rather than return. But i need this function to print and not return unfortunately :(
@AngelE: You can't just say "print binary(3)"?
0

I would make it return a string instead of printing directly, it would make things much simpler. Like this:

def binary(n):
    s = str(n % 2)

    if n >> 1 > 0:
        s += binary(n >> 1)

    return s

print binary(9)

Here's a demo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.