binaryToDecimal = lambda binary: sum([[int(2**index) for index in range(len(binary))][-index-1] for index, char in enumerate(binary) if int(char)])
I wrote a simple function that converts binary strings into decimal integers. How can this be improved/simplified?
I know about the int
function, I wanted to implement the conversion myself.
1 Answer 1
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!
-
\$\begingroup\$ Funny enough, I tested the character at first but moved to int to save characters (I was challenging myself to use the least characters) \$\endgroup\$Hum4n01d– Hum4n01d2018年05月10日 00:35:40 +00:00Commented May 10, 2018 at 0:35
-
1\$\begingroup\$ yes, it's good for code golfing, but not really for performance :) \$\endgroup\$Jean-François Fabre– Jean-François Fabre2018年05月10日 15:12:17 +00:00Commented May 10, 2018 at 15:12
Explore related questions
See similar questions with these tags.
binaryToDecimal = lambda x: str(int(x,2))
\$\endgroup\$