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)
identity
并不是每次都增加x
。我认为混乱可能源于此行:
total, k = total + term(k), k + 1
相当于
total = total + term(k)
k = k + 1
也许这可以使我们更容易看到从k=1
到k=10
的k。每次增加的是k
,而不是x
。