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

后端 未结 5 2020
被撕碎了的回忆
被撕碎了的回忆 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:25

    If you want to do every step in O(1):

    def gen(x):
       i = 2
       for n in range(x + 1):
           yield i
           i <<= 1
    
    >>> list(gen(4))
    [2, 4, 8, 16, 32]
    

    PS: There's a typo in the question and if you want 4 numbers for gen(4), use range(x) instead

提交回复
热议问题