Determining combination of bits
nick at craig-wood.com
Tue Nov 9 07:44:08 CET 2004
Larry Bates <lbates at syscononline.com> wrote:
> Sounds a lot like a homework assignment
> but I'll give you some "hints".
> 1) Use bit shifting operator (>>) and boolean &
> operator to isolate each bit in the integer.
Shifting isn't necessary - D.keys() contains a list of all possible
(for this problem) binary numbers.
> 2) It will be either zero or one. Build up a
> list of these which will represent the power
> of two that each one bit represents.
Whenever you think "build up a list" you should be thinking list
comprehension. A conditional add to a list should make you think of
the if clause of a list comprehension.
>>> def f(n): return [D[i] for i in D.keys() if XXXXX]
['two', 'three', 'five']
['four', 'one', 'five']
I've left XXXXX as an excercise - see 1) above for a hint ;-)
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list