【问题标题】:Generating all possible combinations in a range using numpy in python在python中使用numpy生成范围内所有可能的组合
【发布时间】:2018-04-17 11:57:36
【问题描述】:

我正在寻找一种有效的方法来使用 numpy 或任何更快的方法在某个大范围内生成所有可能的组合。我试过了:

from numpy import *
from itertools import *

dt=dtype('i,i,i,i,i,i')
fromiter(combinations(range(10000000),6), dtype=dt, count=-1)

但我遇到了内存错误,即使它成功了,也可能需要很长时间才能完成。我正在寻找不重复的组合。例如,如果我需要 range(1,5) 中的所有 3 个数字组合,我将得到 (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4 )。

【问题讨论】:

  • 您正在尝试生成 1.3888868e+39 个序列。当然你会得到一个内存错误。
  • 您在寻找什么样的答案?即使你把所有的数字都塞进了一个位(不可能),你仍然没有足够的内存。或者时间。
  • 注意,即使每次迭代花费 1 纳秒 (1.388e39 * 1e-9),它仍然需要 4.4x10^22 年,即已知宇宙年龄的 3.2x10^12 倍需要 1.3888868e39 次迭代。

标签: python numpy combinations


【解决方案1】:

大约有 1,000,000,000,000,000,000,000,000,000,000,000,000,000,000 (1 Septillion) 6 个元素与您正在使用的范围的可能组合。你永远不会处理它们。您能做的最好的事情就是使用迭代器以“惰性方式”处理它们:

for c in combinations(range(10000000),6):
    print(c)

【讨论】:

  • 明白。谢谢
猜你喜欢
  • 2013-01-04
  • 1970-01-01
  • 2017-07-10
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 2017-09-15
  • 1970-01-01
相关资源
最近更新 更多