python - 当在每个循环 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)
解决方案
identity
不会随着x
每次传递而增加。我认为混乱可能源于这一行:
total, k = total + term(k), k + 1
这相当于
total = total + term(k)
k = k + 1
也许这使我们更容易看到我们从 kk=1
到k=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))
推荐阅读
- django - 将更改迁移到数据库时遇到问题 - Python/Django
- linux-kernel - 如何理解 DSDT 表中定义的 ACPI _OSC 方法
- java - 为什么 Java websocket 服务器这么慢?
- vector - 如何在 VHDL 中测试矢量多路复用器的所有情况?
- java - 如何根据多个变量制作随机二维数组?
- mysql - mysql显示表中的数据最大值和总和
- javascript - 用于反应抛出错误中的道具的打字稿传播运算符
- javascript - 如何触发 React 从外部重新渲染
- javascript - 三个 js 平滑底纹显得平坦
- graph - 生成类似 PISA 的图形