我注意到在Julia中使用匿名函数会导致性能下降.为了说明我有两个quicksort实现(取自Julia发行版中的微观性能基准).第一种按升序排序
function qsort!(a,lo,hi)
i, j = lo, hi
while i < hi
pivot = a[(lo+hi)>>>1]
while i <= j
while a[i] < pivot; i += 1; end
while pivot < a[j]; j -= 1; end
if i <= j
a[i], a[j] = a[j], a[i]
i, j = i+1, j-1
end
end
if lo < j; qsort!(a,lo,j); end
lo, j = i, hi
end
return a
end
Run Code Online (Sandbox Code Playgroud)
第二个需要一个额外的参数:一个匿名函数,可用于指定升序或降序排序,或比较更奇特的类型
function qsort_generic!(a,lo,hi,op=(x,y)->x<y)
i, j = lo, hi
while i < hi
pivot = …
Run Code Online (Sandbox Code Playgroud) 我想在Python中的函数参数中传递一个公式,其中公式是其他函数参数的组合.原则上,这将是这样的:
myfunction(x=2,y=2,z=1,formula="x+2*y/z")
6
Run Code Online (Sandbox Code Playgroud)
或更具体:
def myformula(x,y,z,formula):
return formula(x,y,z)
Run Code Online (Sandbox Code Playgroud)
这将允许用户根据x,y和z选择任何算术表达式,而无需创建新函数.
我预见的一种可能性是在函数内的代码行中转换字符串.在Python中有什么可能吗?还是其他任何想法?谢谢