在Python中求和?

Kal*_*iMa 2 python

例如,让我们说,我想总结一下所有的x ^ 2(或任何其他任意函数)为X = 1起,直到找到x ^ 2大于n.这可以在不使用一堆while循环和if-checks的情况下完成吗?

And*_*ark 6

itertools模块为可扩展的解决方案提供了一些很好的功能:

from itertools import takewhile, count

def sum_func(func, n):
    return sum(takewhile(lambda x: x < n, (func(i) for i in count(1))))
Run Code Online (Sandbox Code Playgroud)

例如:

>>> sum_func(lambda x: x**2, 20)  # 1^2 + 2^2 + 3^2 + 4^2
30
Run Code Online (Sandbox Code Playgroud)

如果你想使这也适用于减少函数,你也可以传入测试函数:

def sum_func(func, pred):
    return sum(takewhile(pred, (func(i) for i in count(1))))
Run Code Online (Sandbox Code Playgroud)

例:

>>> sum_func(lambda x: -x*2, lambda x: x > -10)  # -1*2 + -2*2 + -3*2 + -4*2
-20
Run Code Online (Sandbox Code Playgroud)