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

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

    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

    0 讨论(0)
  • 2021-01-19 11:21

    As @JBernardo pointed out, I assume there is a typo in your question.

    def squares(n):
        power = n
        square_list = []
        for i in range(1,n+1):
            square_list.append(2 ** i)
        return square_list
    
    
    print squares(4)
    

    will return

    [2,4,8,16]

    0 讨论(0)
  • 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) ]
    
    0 讨论(0)
  • 2021-01-19 11:23
    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

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题