【问题标题】:When total = total + term(k) is called after every loop x is somehow 1 larger. why?当在每个循环 x 以某种方式大 1 后调用 total = total + term(k) 时。为什么?
【发布时间】:2019-11-26 16:00:00
【问题描述】:

在 Sum_naturals 函数将恒等函数传入“term”中的求和函数之后,当在每个循环 x 以某种方式变大 1 后调用 total = total + term(k) 时。为什么?

def summation(n, term):
    total, k = 0, 1
    while k <= n:
        total, k = total + term(k), k + 1
    return total

def identity(x):
    return x

def sum_naturals(n):
    return summation(n, identity)

sum_naturals(10)

【问题讨论】:

  • 嗨@AJT,欢迎来到 StackOverflow。 identity() 函数没有增加 x。请在问题正文中详细说明您的问题。
  • 请编辑标题以适应 SO 建议:stackoverflow.com/help/how-to-ask
  • 您知道这可以通过def sum_naturals(n):return n*(n+1)//2; sum_naturals(10) 完成,对吗?
  • 提醒一下,当您了解原始问题的解决方案时:这可以简化为算术单行表达式,它是算术级数和:en.wikipedia.org/wiki/Arithmetic_progression#Sum
  • @SayanipDutta 将我的评论打到 1 分钟。

标签: python python-3.x function math while-loop


【解决方案1】:

identity 不会随着每次传递而增加 x。我认为混乱可能源于这一行:

total, k = total + term(k), k + 1

这相当于

total = total + term(k)
k = k + 1

也许这让我们更容易看到我们从k=1k=10查看k。每次都在增加的是k,而不是x

def summation(n, term):
    total, k = 0, 1
    while k <= n:
        total, k = total + term(k), k + 1
    return total

可以替换为

def summation(n, term):
    total = 0
    for k in range(1, n+1):
        total = total + term(k)
    return total

甚至

def summation(n, term):
    return sum(term(k) for k in range(1,n+1))

【讨论】:

  • 我不会混淆 k 每次通过都会增加。如果将代码粘贴到我正在使用的 pythontutor 中,在第 15 步和第 16 步之间,X 现在是 2 而不是 1。在第 13 步,x=1,在第 16 步,x 现在是 2。为什么?
  • 您将参数 x 传递给 identity。如果您将 k 传递给身份 - 在您的代码中,term(k),那么 x 将采用 k 的值。您的代码将k=1,2,3,4...10 传递给identity,因此x 的值也会发生变化。
  • 那里,啊,明白了。它是因为 term(k),它传递了一个更新的 k,随着每个 while 循环增加 1。谢谢。明白了!
猜你喜欢
  • 2013-09-02
  • 2013-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
  • 1970-01-01
  • 2011-11-06
相关资源
最近更新 更多