【问题标题】:a to the power of b without (a**b), Python没有 (a**b) 的 a 的 b 次方,Python
【发布时间】:2017-02-17 14:06:07
【问题描述】:

在没有这个运算符的情况下要求我写 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))

【问题讨论】:

  • return 所以其余的无法访问...
  • 函数只能返回 1 个值。你试图做的事情没有意义。而是返回一个元组。
  • 肯定是无法访问的。口译员是这么告诉我的。这就是我来这里询问的原因。不是经验丰富的程序员的投票游戏又来了……

标签: python if-statement counter


【解决方案1】:

尝试递归:

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

【讨论】:

  • 非常感谢,托拜厄斯!我的问题是我根本无法理解递归。他们似乎让我的头脑爆炸了。我看过一些例子(比如 factorial ),但什么都不懂。
  • @Jewenile 每个人都能理解递归。这当然是一个困难的话题,但值得努力学习。
【解决方案2】:

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

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


print(powerof(5,2))

希望对您有所帮助。

【讨论】:

  • 谢谢。天真没什么不好。我只是一个需要学习一些编码的工程师。不需要更多。
  • 您可以删除if exp==0: return 1 -- exp==0 的情况已经被处理。
  • 感谢@Paul_Hankin,我现在已经相应地编辑了答案。
【解决方案3】:

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

所以,让我们尝试修复您的代码。你为什么要在你的if 语句中返回一些东西?

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

你知道当你返回时,你会退出你的函数吗?这不是你的意思。我猜你想要的是乘以result,只要你没有这样做exp 次。换句话说,您想重复if 语句中的代码,直到您执行了exp 次。你有一个关键字:while。 而while 肯定包括您尝试通过if 提供的条件。

祝你好运!

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

【讨论】:

  • 当然,你是对的。它给出一个数字。以前的一些版本确实返回了其中的两个。对不起。
【解决方案4】:

您可以通过以下方式之一解决任务“在不使用 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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 2014-03-29
    • 1970-01-01
    • 2021-10-06
    • 2016-05-04
    • 2017-01-21
    • 1970-01-01
    相关资源
    最近更新 更多