Python的While循环用于2的幂的乘积

2024-04-19 15:25:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助创建一个使用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)

但这行不通。有人能帮忙吗??在


Tags: andofthewhichreturnfunctionargumentnum
2条回答

这很有效:

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

我想任务是这么说的?在

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

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

^{pr2}$

提示:你可以用数学。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

相关问题 更多 >