Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a list of numbers of the power of 2?

Tags:

python

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.

like image 805
starrynights89 Avatar asked Nov 13 '12 02:11

starrynights89


People also ask

How do you find the power of 2 numbers?

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.

How do you express a number as a sum of powers 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}.

How do you write 2 power N in Python?

Python pow() function returns the result of the first parameter raised to the power of the second parameter.


2 Answers

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) ]
like image 107
mgilson Avatar answered Sep 22 '22 02:09

mgilson


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

like image 28
olivecoder Avatar answered Sep 23 '22 02:09

olivecoder