Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a better way to code this specific algorithm using successively division through 2 which converts decimal numbers into binary numbers without calling a built-in function?

print "Please enter a decimal number."
prompt = '>> '
dec_number = input(prompt)
dec_new = dec_number 
binstr = ''

'''dec2bin'''
while dec_new != 0:
  binstr += str(dec_new % 2)
  dec_new = dec_new // 2

print binstr[::-1]
share|improve this question
    
I just want to learn a bit in order to get more comfortable with loops etc. And 'better' in terms of 'as efficient as it can get under these circumstances' – Stefan Jul 7 at 12:37
    
Sorry for interrupting, but my codes are really just meant as exercises with no intention of writing something professional. I'm a beginner, after all, and want to figure out how things work on my own, and sometimes with your help. – Stefan Jul 9 at 11:49
up vote 7 down vote accepted

In general, your idea is not bad.

The best solution, as far as I read, would be the algorithm Divide by 2 that uses a stack to keep track of the digits for the binary result.

As an intro, this algorithm assumes that we start with an integer greater than 0. A simple iteration then continually divides the decimal number by 2 and keeps track of the remainder.

dec-to-bin

The first division by 2 gives information as to whether the value is even or odd. An even value will have a remainder of 0. It will have the digit 0 in the ones place. An odd value will have a remainder of 1 and will have the digit 1 in the ones place. We think about building our binary number as a sequence of digits; the first remainder we compute will actually be the last digit in the sequence.

That said, we have:

from pythonds.basic.stack import Stack

def divideBy2(decNumber):
    remstack = Stack()

    while decNumber > 0:
        rem = decNumber % 2
        remstack.push(rem)
        decNumber = decNumber // 2

    binString = ""
    while not remstack.isEmpty():
        binString = binString + str(remstack.pop())

    return binString

print(divideBy2(42))

Comments regarding your code:

  1. Why did you do this: dec_new = dec_number ? You could've just use dec_number. There's no need of assigning its value to another variable.
  2. This: dec_new = dec_new // 2 could be as well as the above line of your code rewritten as: dec_new //= 2
  3. The indentation should contain 4 spaces, not 2.

A version that better (than your solution) utilizes the memory would be:

def dec_to_bin(n):
    bits = []

    bits.append(str(0 if n%2 == 0 else 1))
    while n > 1:
        n = n // 2
        bits.append(str(0 if n%2 == 0 else 1))

    bits.reverse()
    return ''.join(bits)

What I did:

  • floor divide all the numbers by two repeatedly until we reach 1
  • going in reverse order, create bits of this array of numbers, if it is even, append a 0 and if it is odd append a 1.

Other ways of doing it:

Using recursion:

def dec_to_bin(x):
    return dec_to_bin(x/2) + [x%2] if x > 1 else [x]

The above solution returns the result as a list which you can later on .join() then apply int() to it.

Another idea that came to my mind is as simple as:

u = format(62, "08b")
>> 00111110
share|improve this answer
1  
Thanks! This is what I have been looking for. I'll try your samples out and see how far I can get though these codes contain a lot of new things I still need to learn. – Stefan Jul 7 at 13:02
    
I strongly recommend you to start step by step. There's no hurry. You can start with this which is absolutely great. Good luck. And if you have questions, just ask. But don't forget, this is only for code reviewing. You can read our help section for more information – Dex' ter Jul 7 at 13:04
    
Now that you have mentioned it, this line really seems to be redundant. The second comment looks interesting, didn't know that this notation also applied to the division operator. Besides that I'll try to use 4 spaces from now on. And thank you for providing the link. Looks like it covers a lot. – Stefan Jul 7 at 13:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.