You are printing each element (1 or 0) into the loop. You should concatenate all the 1/0s and reverse at the end.
Pay attention when you program loops. You are trying to set a value which is built along iterations in a specific iteration. When your script calculates code
value (for example 1
), it reverses that number and jumps to the next iteration, repeating the process.
The solution would be to build an inverse string along all iterations, incrementally. The next code defines an empty string and concatenates 0 or 1 before the previous result.
Example:
# Initialize reverse_code variable
reverse_code = ""
while number != 0:
if number % 2 == 0:
code = "0"
new_number = number //2
number = new_number
else:
code = "1"
new_number = number //2
number = new_number
reverse_code = code + reverse_code
print(reverse_code)
If number = 10
:
1010
Explanation
When while
loop starts iterating, it divides by 2 the number and we want to reverse the result of the division to obtain binary code. Instead of calculate the result we can create the result in calculation time. For this we define reverse_code
as an empty string. In each iteration we will put the new item (1 or 0) before the string, obtaining the inverse string.
reverse_code
values in iterations when number=10
:
Iteration 0:
code
= 0
reverse_code
= code
+ reverse_code
= "0" + "" = "0"
Iteration 1:
code
= 1
reverse_code
= code
+ reverse_code
= "1" + "0" = "10"
....
Iteration N:
code
= 1
reverse_code
= code
+ reverse_code
= "1" + "010" = "1010"
Another question to comment is your code optimization. Watching your code, if the else-if you have new_number
and number
variables assignation which is not affected by the previous variables code
. You can extract common factor and simplify the code. The code should be as follows:
# Initialize reverse_code variable
reverse_code = ""
while number != 0:
# Calculate the `code` value
if number % 2 == 0:
code = "0"
else:
code = "1"
# Putting this here simplifies duplicate instructions
new_number = number //2
number = new_number
# Putting 0 or 1 (code) before semi-built string (reverse_code)
reverse_code = code + reverse_code
print(reverse_code)