I need to create function to convert decimal numbers to binary, and visualise that process in this way:
for example 15:
15|1
7 |1
3 |1
1 |1
number 15 in binary is 1111 (from bottom to up).
I keep trying to do that, but I don't even know, than my function is correct. I know that python has a "bin" built in function, but its not possible to use it for that visualisation (or am I wrong?).
My last code:
FinalList = []
dividedList = []
number = 29
while number != 1:
divided = number%2
number = int(number/2)
FinalList.append(divided)
dividedList.append(number)
print(divided)
if number == 0:
print(0)
FinalList.append(divided)
dividedList .append(0)
else:
print(1)
FinalList.append(1)
dividedList.append(1)
print(FinalList)
print(dividedList)
Can someone help me with that?
my output for number 230:
[0, 1, 1, 0, 0, 1, 1, 1]
[115, 57, 28, 14, 7, 3, 1, 1]
and should be:
[0, 1, 1, 0, 0, 1, 1, 1]
[230,115, 57, 28, 14, 7, 3, 1]
Hope this helps!
Minor change to your code
FinalList = []
dividedList = []
number = 29
print(bin(number))
while number != 1:
_new_number, divided = divmod(number, 2)
print("{}|{}".format(number, divided))
number = _new_number
FinalList.append(divided)
dividedList.append(number)
if number == 0:
print('0|0')
FinalList.append(divided)
dividedList .append(0)
else:
print('1|1')
FinalList.append(1)
dividedList.append(1)
print(FinalList[::-1]) # should match with the `bin` result
print(dividedList)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments