N
Nick Craig-Wood
Larry Bates said:Sounds a lot like a homework assignment
Indeed!
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.
D={1:'one',2:'two',4:'three',8:'four',16:'five'}
def f(n): return [D for i in D.keys() if XXXXX] ....
f(9) ['four', 'one']
f(22) ['two', 'three', 'five']
f(25)
['four', 'one', 'five']
I've left XXXXX as an excercise - see 1) above for a hint ;-)