Hi folks! I gave myself a simple task of creating a function that turns binary numbers into decimal and was just wondering is there any way to make it a little bit more compact without using any extra modules? purely for practicing writing a tighter code.
def bi_to_dec(x):
y=str(x)
pwer= 0
totl = 0
for i in y[::-1]:
power_multipler = int(i)*2**pwer
totl+=power_multipler
pwer+=1
return print(totl)
bi_to_dec(10111)
Cheers :)
There are several options pending of datatype of input and expected datatype of output
There is built-in function int() which doesn't fall under 'using any extra modules'.
>>> int('101010', 2) # input is string, output is integer
42
There is also f-string in 3.6 <= Python which can be used for conversion:
>>> f'{0b101010:#0}' # input is binary, output is string
'42'
bi_to_dec
function can be rewritten to avoid conversion into str by using built-in
divmod()
:
def binary_to_int(binary):
integer = 0
power = 0
while binary:
binary, reminder = divmod(binary, 10)
integer += reminder*2**power
power += 1
return integer
Note about
bi_to_dec
- I recommend not to return print. Return value and let programmer decide whether it is necessary display this value or use it in expressions/statements.
Simplest:
def binary_to_int(value: str) -> int:
return int(value, base=2)
Own implementation:
def binary_to_int(value: str) -> int:
if not set("01").issuperset(value):
raise ValueError(f"Not allowed value: {value}")
result = 0
for bit, char in enumerate(reversed(value)):
if char == "1":
result += 2 ** bit
return result
The type hints are not required. I just use them to show which types a function should take and which return types a function has.