Python 2 的幂乘积的 While 循环

Python While Loop for Products of Powers of 2

我需要帮助创建一个使用 while 循环的函数,以便找到 2 的幂的乘积。

问题如下:

Create a Python function called productOfPowersOf2 which takes two arguments, both of which are non-negative integers. For purposes of this problem, let's call the first argument exp1 and the second argument exp2. Your function should compute and return (not print) the product of all powers of 2 from 2exp1 to 2exp2. Here are some examples of how your function should behave:

>>> productOfPowersOf2(0,0)
1
>>> productOfPowersOf2(1,1)
2
>>> productOfPowersOf2(1,2)
8
>>> productOfPowersOf2(1,3)
64

我写的是:

def productsOfPowersOf2(exp1,exp2):
    total=0
    num=0
    while num<=exp2:
        total=(2**exp1)*(2**(exp1+num))
        num=num+1
    return(total)

但这不起作用。有人可以帮忙吗??

我假设作业是这样说的?

Your function should compute and return (not print) the product of all powers of 2 from 2exp1 to 2exp2

1) 您没有服用累积产品;您只将 total 重新分配给下一个值。

total=(2**exp1)*(2**(exp1+num))

换句话说,当循环退出时,你只会得到这个,如果我不得不猜测的话,它可能总是大于你想要的值

total=(2**exp1)*(2**(exp1+exp2))

提示:您可以使用数学。 x^y * x^z = x ^ (y + z)。在取二的幂之前对指数求和。

剧透

def productOfPowersOf2(exp1,exp2): total = 2**exp1 exp1 += 1 while exp1 <= exp2: total *= 2**exp1 exp1 += 1 return total

效果很好:

def productOfPowersOf2(a,b): 
    return reduce(lambda x,y: x*y ,[2**i for i in range(a,b+1)])