def problem(n):
myList = []
for j in range(0, n):
number = 2 ** j
myList.append(number)
return myList
I want this code to return the powers
import math
n = input()
a = [i for i in xrange(2, n+1) if (math.log(i)/math.log(2)).is_integer()]
print a
>>> [2, 4, 8, 16 ...]
Returns list of powers of 2 less than or equal to n
Explanation:
A number can only be a power of 2 if its log divided by the log of 2 is an integer.
eg. log(32) = log(2^5) = 5 * log(2)
5 * log(2) when divided by log(2) gives 5 which is an integer.
Also there will be floor(math.log(n, 2)) elements in the list, as that is the formula for the number of powers of 2 below n if n itself is not a power of 2