0
\$\begingroup\$
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.

\$\endgroup\$
6
  • \$\begingroup\$ what about using python: binaryToDecimal = lambda x: str(int(x,2)) \$\endgroup\$ May 9, 2018 at 18:41
  • \$\begingroup\$ I'm aware that you can do that :) I just wanted to implement it myself \$\endgroup\$
    – Hum4n01d
    May 9, 2018 at 18:41
  • \$\begingroup\$ Well, readability could be improved a lot by not using too much list comprehensions together :) \$\endgroup\$
    – IEatBagels
    May 9, 2018 at 18:42
  • 1
    \$\begingroup\$ Definitely, I did that on purpose though to make it as compact as possible \$\endgroup\$
    – Hum4n01d
    May 9, 2018 at 18:43
  • 2
    \$\begingroup\$ I added reinventing-the-wheel, because that's what you're doing here: inventing this even though a standard implementation exists. In the future, you may want to add this tag yourself, to signify to other users that you're knowingly not using the standard implementation. \$\endgroup\$
    – Daniel
    May 9, 2018 at 19:28

1 Answer 1

2
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\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
    May 10, 2018 at 0:35
  • \$\begingroup\$ yes, it's good for code golfing, but not really for performance :) \$\endgroup\$ May 10, 2018 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.