【问题标题】:Cartesian product with conditions带条件的笛卡尔积
【发布时间】:2020-07-14 02:41:38
【问题描述】:

下面的代码可以很好地生成所有可以组合数字的方法,这些数字在步长为 2 时总和为某个值。

增加to_val 和axislengh 会对执行造成重大影响。

有没有办法提高下面的效率? 如果是这样,你能分享一个例子吗?

import itertools
import pandas as pd

def yielder(ctproduct):
    for element in ctproduct:
        #Making sure the sum of the numbers is between from_val and to_val.
        if to_val>sum(element)>=from_val:
            yield element
    

axislengh= 4
from_val= 100 
to_val= 104
step=2

#Maybe this is not the best way.
args =[[i for i in range(0, to_val, step)] for x in range(axislengh)]
ctproduct= itertools.product(*args)  


df=pd.DataFrame(yielder(ctproduct))

df

【问题讨论】:

  • 也许看看 numpy ,它是 arange 函数。你也可以用 numpy.where 替换你的 yielder
  • 我觉得可能还有一个递归/DP解决方案。

标签: python numpy


【解决方案1】:

由于您使用的所有 for 循环,您的代码可能运行缓慢。您可以通过消除这些循环、通过向量化或对同一对象的重复引用来显着加快代码速度。

args = axislength * (range(0, to_val, step),)

ctproduct = np.array(list(itertools.product(*args)))
s = ctproduct.sum(axis= 1)

mask = (from_val <= s) & (s < to_val)

df = pd.DataFame(ctproduct[mask])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-30
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多