Determining combination of bits
Peter Abel
PeterAbel at gmx.net
Tue Nov 9 12:50:50 EST 2004
"Sean Berry" <sean at buildingonline.com> wrote in message news:<x3Qjd.121786$hj.41260 at fed1read07>...
> Say I have a dictionary like the following
>
> {1:'one',2:'two',4:'three',8:'four',16:'five', etc...}
Dont know exactly what your dictionary should represent.
Since 2**0 = 1
2**1 = 2
2**2 = 4
etc.
So I would have expected something like:
{1:'zero',2:'one',4:'two',8:'three',16:'four',32:'five', etc...}
>
> and I am given some numbers, say 22, 25, and 9. I want to determine the
> keys, powers of 2, that comprise the number.
>
> Ex. 22 = 16+4+2
> 25 = 16+8+1
> 9 = 8+1
> ...etc...
>
> How do I get these keys?
Solution No. XXXXXXXX:
>> def fn(n):
... number=n
... if n<=0:
... return 'n must be greater 0'
... keys=[]
... i=1
... while n:
... if n&1:
... keys.append(i)
... n=n>>1
... i*=2
... keys.reverse()
... l=map(str,keys)
... print '%d = %s' % (number,'+'.join(l))
... return keys
...
>>> print fn(22)
22 = 16+4+2
[16, 4, 2]
>>> print fn(25)
25 = 16+8+1
[16, 8, 1]
>>> print fn(255)
255 = 128+64+32+16+8+4+2+1
[128, 64, 32, 16, 8, 4, 2, 1]
>>>
Sorry I have only Python 2.2. and though I'm a one-liner-fan my
solution should be clear.
Regards Peter
More information about the Python-list
mailing list