首页 > 解决方案 > 当在每个循环 x 以某种方式大 1 之后调用 total = total + term(k) 时。为什么?

问题描述

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

标签: pythonpython-3.xfunctionmathwhile-loop

解决方案


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

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

这相当于

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

也许这使我们更容易看到我们从 kk=1k=10。是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))

推荐阅读