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 of 2 based upon the first n powers of 2. So for example, if I enter in 4, I want it to return [2,4,6,8,16]. Right now, the code returns [1,2,4,8] if I enter in 4. I think it's my range that's messing up the code.
A simple method for this is to simply take the log of the number on base 2 and if you get an integer then the number is the power of 2.
Given an integer N, the task is to count the number of ways to represent N as the sum of powers of 2. Explanation: All possible ways to obtains sum N using powers of 2 are {4, 2+2, 1+1+1+1, 2+1+1}.
Python pow() function returns the result of the first parameter raised to the power of the second parameter.
just use range(1,n+1)
and it should all work out. range
is a little confusing for some because it does not include the endpoint. So, range(3)
returns the list [0,1,2]
and range(1,3)
returns [1,2]
.
As a side note, simple loops of the form:
out = []
for x in ...:
out.append(...)
should typically be replaced by list comprehensions:
out = [ 2**j for j in range(1,n+1) ]
Yet another simple and efficient solution (every step in O(1)) without the power operator:
def problem(n):
return [1 << i for i in range(n)]
The 1 << i operations is a bitwise operation which translates to 2 ^ i for i integer positive.
https://en.wikipedia.org/wiki/Arithmetic_shift
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With