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

后端 未结 5 2049
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 10:56
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

5条回答
  •  难免孤独
    2021-01-19 11:23

    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) ]
    

提交回复
热议问题