【发布时间】: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