a没有(a ** b),Python的b的力量

时间:2017-02-17 14:06:07

标签: python if-statement counter

在练习中挣扎,要求我写一个没有这个操作符的**。试图自己写点东西但是没有得到正确的结果。而不是一个值得到两个,都不正确。好像柜台并没有真正增加。我可以寻求帮助吗?谢谢!

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

4 个答案:

答案 0 :(得分:2)

尝试递归:

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循环中执行此操作,但递归更紧凑。

答案 1 :(得分:1)

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

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


print(powerof(5,2))

希望它有所帮助。

答案 2 :(得分:0)

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

因此,让我们尝试修复您的代码。你为什么要在<script src="//d3js.org/d3.v4.min.js"></script>声明中回复某些内容?

if

你知道当你回来时,你退出了你的职能吗?这不是你的意思。我想你想要的是,只要你没有return result return counter # here it says "unreachable code". Can I not return more variables at the same time? 次,就会乘以result。换句话说,您希望重复exp语句中的代码,直到if次为止。您有一个关键字:expwhile肯定包含您尝试为while提供的条件。

祝你好运!

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

答案 3 :(得分:0)

您可以通过以下其中一种方式来解决任务“将a提升到b的力量,而无需使用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.