Python get number from group of numbers
numbers, python
Solution
Assuming that the possible numbers are always powers of two, you basically want to convert the number to binary format. This is easy with the built-in bin function:
>>> mylist = [int(x) for x in bin(23)[2:]]
>>> print mylist
[1, 0, 1, 1, 1]
To get the output exactly like you showed in your question:
>>> for i, j in enumerate(mylist):
... print '%ix %i' % (j, 2**(len(mylist)-i-1))
...
1x 16
0x 8
1x 4
1x 2
1x 1
Problem
I want to find out with how many times I can build a number from a group of numbers: ``` possible_numbers = 1, 2, 4, 8, 16 ``` If I want number 23 I need ``` 1x 16 0x 8 1x 4 1x 2 1x 1 ``` Is there any built in function in Python to do this? Edit: The numbers are fixed to 1,2,4,8,16,32,64,128. Multiple selections are possible. Since there is no build in function, I'll code it myself.