为什么身份函数每次通过都会增加x? (Python 3.5)

问题描述 投票:-1回答:1
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)
python python-3.x
1个回答
0
投票

identity并不是每次都增加x。我认为混乱可能源于此行:

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

相当于

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

也许这可以使我们更容易看到从k=1k=10的k。每次增加的是k,而不是x

© www.soinside.com 2019 - 2024. All rights reserved.