Q:

What is the fastest way to represent number as the sum of powers of two in python

For example 
>>> two_powers(42)
>>> (2, 8, 32)

My current naive implementation (taken from here) looks like that
def two_powers(num):
    return tuple(2 ** i for i, j in enumerate(bin(num)[-1: 1: -1]) if j == '1')

But I hope there're faster ways to do this.

A:

Try this:
def two_powers(num):
    powers = []
    while num != 0:
        powers.append(num & -num)
        num = num & (num - 1)
    return powers

