...同时仍然在函数中保持可执行文件.
这背后的想法是我想创建一个求和函数.这是我到目前为止所拥有的:
def summation(n, bound, operation):
if operation is None and upper != 'inf':
g = 0
for num in range(n, limit + 1):
g += num
return g
else:
pass
Run Code Online (Sandbox Code Playgroud)
但总结通常是关于无限收敛系列(我使用它'inf'),操作应用于每个术语.理想情况下,我希望能够编写print summation(0, 'inf', 1 / factorial(n))并获得数学常数e,或者def W(x): return summation(1, 'inf', ((-n) ** (n - 1)) / factorial(n))获得Lambert W函数.
我想到的只是将相应的算法作为字符串传递,然后使用该exec语句来执行它.但我不认为这会完成整个事情,并且使用exec可能是用户输入的代码显然是危险的.
在Python中,函数是一流的,也就是说它们可以像任何其他值一样使用和传递,因此您可以使用函数:
def example(f):
return f(1) + f(2)
Run Code Online (Sandbox Code Playgroud)
要运行它,您可以定义一个这样的函数:
def square(n):
return n * n
Run Code Online (Sandbox Code Playgroud)
然后将其传递给您的其他功能:
example(square) # = square(1) + square(2) = 1 + 4 = 5
Run Code Online (Sandbox Code Playgroud)
lambda如果它是一个简单的表达式,您还可以使用以避免必须定义新函数:
example(lambda n: n * n)
Run Code Online (Sandbox Code Playgroud)