Python Forum
Simplifying function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simplifying function
#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


Messages In This Thread
Simplifying function - by GJG - Dec-21-2020, 03:36 AM
RE: Simplifying function - by perfringo - Dec-21-2020, 07:32 AM
RE: Simplifying function - by DeaD_EyE - Dec-21-2020, 10:21 AM

Forum Jump:

User Panel Messages

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