Of course, the most efficient solution would be to let python parse the binary string as integer ;)
binaryToDecimal = lambda x: int(x,2)
But you already know that, so what about simplifying your code like this:
binaryToDecimal = lambda binary: sum(1<<(len(binary)-index-1) for index, char in enumerate(binary) if char=='1')
- removing the creation of the inner list comprehension just to pick one value
- not using power but bitshift (integer computation, faster, more accurate)
- don't create a list to pass to
sum
, pass a generator comprehension (it's faster, saves memory)
- in your condition, don't convert your number to integer, just test against the char value (it's faster)
Keep in mind that your parsing has no error checking!
binaryToDecimal = lambda x: str(int(x,2))
\$\endgroup\$