I\'m trying to create a function that receives a number as an argument and performs actions on that number to find out its closest powers of 2 that will then add up to that
The idea is to convert the number to binary and then get powers of two from the binary representation:
#!/usr/bin/env python
def get_powers(n):
"""Get positive powers of two which add up to n.
Parameters
----------
n : positive integer
Returns
-------
list of integers which are powers of 2
Examples
--------
>>> get_powers(14)
[2, 4, 8]
>>> get_powers(5)
[1, 4]
"""
get_bin = lambda x: x >= 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:]
bin_str = get_bin(n) # convert n to a binary string
powers = []
for i, digit in enumerate(bin_str[::-1]):
if digit == '1':
powers.append(2**i)
return powers