1

I'm trying to write a script which converts a given integer number into a binary number using recursion. Here's the code that I've written:

def dec2bin(n):
    if n > 0:
        if n%2 == 0:
            li.append(0)
        else:
            li.append(1)
        return dec2bin(n/2)    
    else:
        aa = li[::-1]
        for e in aa:
            print e,    
n = int(raw_input())
li = []
dec2bin(n)

However, this code keeps on running and never outputs the correct answer. What seems to be the problem with this code?

16
  • n here isn't a decimal number, it's an int, which has no inherent base (or, if you want to stretch it and say it has one, the inherent base is binary). Commented May 1, 2015 at 22:59
  • So to be more correct this function isn't converting decimal to binary it is just printing a positive integer in binary. That is if it worked. Commented May 1, 2015 at 23:00
  • 2
    keeps on running and never outputs the correct answer I think you are forgetting to enter an input for raw_input() and it just waits for your input. Commented May 1, 2015 at 23:03
  • 3
    @Marein: If it's divisible by two, that means its last bit is 0. Commented May 1, 2015 at 23:04
  • 1
    @Marein I have used the algorithm mentioned on the following link for my code: interactivepython.org/courselib/static/pythonds/BasicDS/… Commented May 1, 2015 at 23:05

3 Answers 3

2

Similar to Brad Budlong's solution, but creating the list at the lowest level of recursion instead of using a global or a second argument. (This is Python 3.3 so print is a function; adjust for Python 2.7 if desired. Also using the // operator instead of /)

def dec2bin(n):
    if n == 0:
        return []
    else:
        r = dec2bin(n//2)
        r.append(n%2)
        return r

print(dec2bin(10))
print(dec2bin(42))
Sign up to request clarification or add additional context in comments.

1 Comment

Nice. This is probably the sane solution.
2

Here is an alternative to think about since you are investigating recursion. If you switch the order of the append and the recursive call, then you don't have to reverse the list at the end. This lets the recursion defer the MSB until after the LSBs have already been handled. In the end it does the same thing, but with less complication.

def dec2bin(n):
    if n > 0:
        dec2bin(n/2)
        li.append(n%2)
        print n%2,

I also removed the return statement that you had in your code since you aren't returning anything. This function just modifies li and prints.

1 Comment

@Blckknght You should try and run it and you will see that it prints MSB down to LSB. Note that the recursive call happens before the print, so the most deeply recursive call (the MSB) prints first
1

It works for me, as it does for others in the comments.

However, its use of a global variable to store results is kind of really ugly and exposing you to various interferences, I would never want to see that in production code. Ditto for the prints.

You could edit it thus:

def dec2bin(n, li=None):
    if li is None:
        li = list()
    if n == 0:
        return li[::-1]
    else:
        if n%2 == 0:
            li.append(0)
        else:
            li.append(1)
        return dec2bin(n/2, li)    


print dec2bin(1) # [1]
print dec2bin(3) # [1, 1]
print dec2bin(8) # [1, 0, 0, 0]
print dec2bin(10) # [1, 0, 1, 0]

Pay special attention to that li = list() - see http://effbot.org/zone/default-values.htm

Also note that by replacing li.append(0) with [0]+li and doing the same for the odd case you can do without the reversing (for a small price in readability).

2 Comments

I'm not sure li = [0] + li would be any less readable… but if you think it is, why not li.insert(0, 0)? (Of course there is a cost in performance; you're trading a linear-time reversal for quadratic-time repeatedly shifting the list… but in this use case I doubt that would ever matter, and if it did, you'd want to test it anyway; until you get to huge numbers, the incredibly low constant multiplier on shifting the list may mean it's not a problem…)
I don't know, append seems the most readable to me, but we are splitting hairs.

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.