1

I'm looking for the out put of this, which is how i get Binary code using the divide 2 method

number= int(input(22))
22 / 2 = 11 R 0
11 / 2 = 5 R 1
5 / 2 = 2 R 1
2 / 2 = 1 R 0
1 / 2 = 0 R 1
answer = 10110
print(answer)

With the code I currently have, I'm getting the output 11110. The remainder is what I need to put into a list or a string, and I'm guessing I need to use a While loop, or a for loop.

Here is my code:

binar=""
number=0
while number<=0:
    try:
        number=int(input("Enter a number"))
    except:
        print("That is not a number!")
        continue
print(number)
if (number % 2) == 0:
    num=0
    binar = str(num) + binar
else:
    num=1
    binar = str(num) + binar
while int(number) > 1:
    number=int(number)/2
    print(number)
    if (number % 2) == 0:
        num=0
        binar = str(num) + binar
    else:
        num=1
        binar = str(num) + binar
print(binar)

It's really sloppy. I do have the begging making sure the input is a actual number, and not string. The number can not be 0, or a negative.

0

3 Answers 3

2

You can use a recursion function for that :

def binary(a,l=[]):
 if a>0:    
    l.append(a%2)
    return binary(a/2)
 else:
    return ''.join(map(str,l[::-1]))

print binary(22)

result :

10110

In this function while a>0 we append a%2 to a list and call function with a/2 at last we would have a list that we need to reverse (l[::-1]) and convert to string (map(str,l[::-1])) and at last concatenated (''.join()) !

1

I think your solution is too complicated.

You showed that you want to calculate the result and the remainder of a division of a number by 2, then save the remainder, set the result as new number and do it again until the result ist zero.

For that purpose there is a divmod function in python:

result, remainder = divmod(dividend, divisor)

You can use it after you got the number:

remainders = []
while number:
    number, remainder = divmod(number, 2)
    remainders.append(remainder)
print "".join([str(r) for r in remainders[::-1]])
0

Import math and use the code math.ceil after you divide the number by two. It will look something like this

if (number % 2) == 0:
    num=0
    binar = str(num) + binar
else:
    num=1
    binar = str(num) + binar
while int(number) > 1:
    number=int(number)/2
    number=math.ceil(int(number))
    print(number)
    if (number % 2) == 0:
        num=0
        binar = str(num) + binar
    else:
        num=1
        binar = str(num) + binar

That will solve the problem. And to print in revers just do print(name[::-1])

Your Answer

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

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