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


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