我的理解是itertools functionsare written in C。如果我想加速这个示例代码:
import numpy as np
from itertools import combinations_with_replacement
def combinatorics(LargeArray):
newArray = np.empty((LargeArray.shape[0],LargeArray.shape[0]))
for x, y in combinations_with_replacement(xrange(LargeArray.shape[0]), r=2):
z = LargeArray[x] + LargeArray[y]
newArray[x, y] = z
return newArray
既然combinations_with_replacement
是用C编写的,这是否意味着它不能被加速?请告知。在
提前谢谢。在
确实,
combinations_with_replacement
是用C编写的,这意味着您不太可能加快这部分代码的实现。但是大部分代码并没有花在寻找组合上:而是花在执行加法的for
循环上。你真的,真的,真的想避免这种循环,如果有可能的话,当你使用numpy。此版本将通过the magic of broadcasting执行几乎相同的操作:例如:
^{pr2}$区别在于}使矩阵对称。如果你真的想避免把每样东西都加两次,你也许可以,但我一时想不出该怎么做。在
combinatorics
使下三角成为随机胡言乱语,其中{哦,还有另一个区别:
相关问题 更多 >
编程相关推荐