a 的 b 次方,不带 (a**b),Python

a to the power of b without (a**b), Python

在没有这个运算符的情况下要求我写 a**b 的练习很困难。试图自己写一些东西,但没有得到正确的结果。而不是一个值得到两个,两者都不正确。似乎计数器并没有真正增加。我可以寻求帮助吗?谢谢!

def powerof(base,exp):
  result=1
  counter=0
  # until counter reaches exponent, go on
  if counter<=exp:
    # result multiplies itself by base, starting at 1
    result=result*base
    # increase counter
    counter=counter+1
    return result
    return counter  # here it says "unreachable code". Can I not return more variables at the same time?
  else:     # counter already reached exponent, stop
    return

# I want to print 2**8. Suprisingly getting two (incorrect) values as a result
print(powerof(2,8))

尝试递归:

def powerof(base,exp):
    if exp == 0:
        return 1
    if exp == 1:
        return base
    return base * powerof(base, exp-1)

# I want to print 2**8. Suprisingly getting two (incorrect) values as a result
print(powerof(2,8))

所以它所做的是,它在减少指数的同时调用自己,因此调用看起来像: 2*(2*(2*2))) ... 执行时。 您也可以在 for-loop 中执行此操作,但递归更紧凑。

天真的实现(不是最好的解决方案,但我认为你应该能够遵循这个):

def powerof(base, exp):
    results = 1
    for n in range(exp):
        results *= base
    return results


print(powerof(5,2))

希望对您有所帮助。

我当然也会推荐递归,但显然这不是一个选择;-)

所以,让我们尝试修复您的代码。为什么要在 if 声明中尝试 return 某些内容?

return result
return counter  # here it says "unreachable code". Can I not return more variables at the same time?

您知道当您 return 时,您会退出您的功能吗?这不是你的意思。我猜你想要的是乘以 result 只要你没有这样做 exp 次。换句话说,您想重复 if 语句中的代码,直到重复 exp 次。您有一个关键字:whilewhile 当然包括您试图通过 if.

提供的条件

祝你好运!

编辑:顺便说一句,我不明白你为什么说你得到了两个结果。这很可疑,你确定吗?

您可以通过以下方式之一解决任务"raise a to the power of b without using a**b":

>>> a, b = 2, 8
>>>
>>> pow(a, b)
>>> a.__pow__(b)
>>>
>>> sum(a**i for i in range(b)) + 1  # Okay, technically this uses **.
>>>
>>> import itertools as it
>>> from functools import reduce
>>> import operator as op
>>> reduce(op.mul, it.repeat(a, b))
>>>
>>> eval('*'.join(str(a) * b))  # Don't use that one.