Reputation: 13
I am trying to created a function that takes in a Decimal represented value and converts it into Binary represented value.
Assuming the argument is always an integer:
import math
def binary_decimal_converter(x):
binary_representation = 0
number = x
while number != 0:
n = 1
while x not in range(n,n*2):
n *= 2
binary_representation += 10**(int(math.log(n,2)))
number -= n
return binary_representation
The problem:
If x is in the list below, the program runs normally.
[1, 2, 4, 8, 16, 32, 64, 128....]
But if any other number is used, the program gets stuck in an unbreakable loop.
Why the loop:
while number != 0: #line 24
cannot run twice?
Upvotes: 1
Views: 83
Reputation: 31060
You're assigning number = x
and then using both:
import math
def binary_decimal_converter(x):
binary_representation = 0
number = x
while number != 0:
n = 1
while x not in range(n,n*2): # CHANGE x TO number
n *= 2
binary_representation += 10**(int(math.log(n,2)))
number -= n
return binary_representation
If you change x
to number
on the specified line, it works. x
is not being updated, number
is.
Upvotes: 1