1
\$\begingroup\$

There is no input validation for this, but that aside, I would appreciate it if anyone could help me improve the logic of this script.

import math
#Input
num = input("Enter a whole number: ")

#Floors input in case of a non whole number
decimal = math.floor(float(num))

#Variables
exp = 0
divTwo = 1
zeros = 0
total = ""
if decimal < 0:
    total += str('-')
    decimal = -decimal
if decimal == 0:
    total = str('0')
else:
    #Loops while remainder is > 0.
    while int(decimal) > 0:

        #Increases exponent by one if 2^exp is less than or equal to the remainder.
        if 2 ** exp <= int(decimal):
                exp += 1

        else: #Multiplies 2 by the exponent and places zeros in between 1s. Also subtracts from the exponent.
                exp -= 1

                #Determines whether or not to subtract from the remainder and add a '1' to the binary translation or just add a '0' to the binary translation.
                if 2 ** exp <= int(decimal):

                        #Counts how many zeros need to be added to the end of the binary translation.
                        if 2 ** exp == int(decimal):
                                divTwo = int(decimal)

                                #Loops until all remaining zeros have been accounted for.
                                while divTwo > 1:
                                        divTwo = divTwo / 2
                                        zeros += 1

                        decimal = int(decimal)
                        decimal -= 2 ** exp
                        total += str('1')

                else:
                        total += str('0')

#Places remaining zeros.
while zeros > 0:
        total += str('0')
        zeros -= 1


#Displays answer.
print ('Binary: ' + total)
input()

#
#
#Or 'bin(decimal)' works too, but this was for fun
#
#

Here is a working version of the script.

\$\endgroup\$
  • 1
    \$\begingroup\$ Just to be sure. You know you can do "{0:b}".format(num) right? \$\endgroup\$ – N3buchadnezzar Jun 30 '16 at 21:23
  • \$\begingroup\$ I haven't looked into formatting that much. \$\endgroup\$ – Confettimaker Jun 30 '16 at 21:27
  • \$\begingroup\$ What about bin(x)[2:] then? \$\endgroup\$ – N3buchadnezzar Jun 30 '16 at 21:32
  • 2
    \$\begingroup\$ I did this with the intention of not using bin() \$\endgroup\$ – Confettimaker Jun 30 '16 at 21:36
2
\$\begingroup\$
  • You can remove half of you code.
    You need the variables exp, total and decimal. The rest are just noise.

  • You should remove all the int(decimal)s, decimal is only ever subtracted from, and so it's not going to become a float. And so these are not needed.

  1. You can remove all the code in if 2 ** exp == int(decimal):, instead just use exp as you do zeros.

  2. You should split your while loop so that it only does one thing at a time. You want an int log and then a while loop that converts the input to binary.

  3. You can replace while zeros > 0: with Pythons way to duplicate strings. 0 * zeros.

  4. You should make this a function.

This leads to code like:

def binary(number): # 4
    output = ''
    if number < 0:
        output = '-'
        number = -number

    exp = 1
    while 2 ** exp <= number: # 2
        exp += 1

    while number > 0:
        exp -= 1
        if 2 ** exp <= number:
            number -= 2 ** exp
            output += '1'
        else:
            output += '0'

    return output + '0' * exp # 1, 3


number = int(input("Enter a whole number: "))
print('Binary: ' + binary(number))
\$\endgroup\$
  • \$\begingroup\$ It works for the most part, however it freezes if you input 2. Everything above 2 works. Even 1 works. \$\endgroup\$ – Confettimaker Jul 1 '16 at 14:18
  • \$\begingroup\$ @Confettimaker That's correct, I mistakenly at some point removed the = from 2 ** exp <= number. \$\endgroup\$ – Peilonrayz Jul 1 '16 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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