Ixiaus parnell.s at comcast.net
Thu Oct 18 08:06:24 CEST 2007

```> 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

Thank you for this reply, I only wish I could come up with functions
so elegantly refined!

I know '<<' is shifting x over by n bits; but could you point me to
some literature that would explain why it is the same as "x*2**n"?
(Googling only returns bit shift, but doesn't necessarily explain the
manner in which you are using it)

I will have to read up more on Generators, but maybe you can give me a
lowdown on why
sum([1 << k for k, i in enumerate(reversed(val)) if int(i)]) is less
efficient than using a Generator (is the generator a 'temporary'
list?)
sum(1 << k for k, i in enumerate(reversed(val)) if int(i))

-- Parnell Springmeyer

```