Python Forum
Simplifying function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simplifying function
#1
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 :)
Reply
#2
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.
GJG likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
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.
GJG likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020