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 best and fastest way to do this is, of course, with binary numbers, but here's a way with a generator:
def powers_finder(num):
d = []
while sum(d) < num:
p = powers_of_2()
a=b=1
while sum(d)+a<=num:
b=a
a = next(p)
d.append(b)
d.reverse()
return d
def powers_of_2():
n=1
while 1:
yield n
n*=2
>>> print(powers_finder(5))
[1, 4]
>>> print(powers_finder(8))
[8]
>>> print(powers_finder(9))
[1, 8]
>>> print(powers_finder(14))
[2, 4, 8]