Paul Hankin paul.hankin at gmail.com
Thu Oct 18 00:23:58 CEST 2007

```On Oct 17, 10:58 pm, Ixiaus <parnel... at comcast.net> wrote:
> Thank you for the quick responses.
>
> I did not know that about integer literals beginning with a '0', so
> thank you for the explanation. I never really use PHP except for
> handling basic forms and silly web stuff, this is why I picked up
> Python because I want to teach myself a more powerful and broad
> programming language.
>
> With regard to why I asked: I wanted to learn about Binary math in
> conjunction with Python, so I wrote a small function that would return
> a base 10 number from a binary number. It is nice to know about the
> int() function now.
>
> Just for the sake of it, this was the function I came up with:
>
> def bin2dec(val):
>     li = list(val)
>     li.reverse()
>     res = [int(li[x])*2**x for x in range(len(li))]
>     res.reverse()
>     print sum(res)
>
> Now that I look at it, I probably don't need that last reverse()
>
> def bin2dec(val):
>     li = list(val)
>     li.reverse()
>     res = [int(li[x])*2**x for x in range(len(li))]
>     print sum(res)

Right idea: now to remove all those intermediate lists you construct.
1. reversed(val) creates an iterator that runs over the elements (here
of a string) in reverse order.
2. enumerate() is usually better than using an explicit list index.
3. You can use a generator in your sum to avoid constructing the final
list.

Applying these to your function, and noting that n << k is nicer than
n * 2 ** k, we get a one-liner:

def bin2dec(val):
return sum(int(i) << k for k, i in enumerate(reversed(val)))

Or a slightly nicer alternative is to filter the generator using 'if':

def bin2dec(val):
return sum(1 << k for k, i in enumerate(reversed(val)) if int(i))

--
Paul Hankin

```