【发布时间】:2018-08-28 16:40:34
【问题描述】:
我的问题
我正在尝试从一个非常大的笛卡尔积中生成一小部分可能的组合。我的输入将是一个数组数组,但每个数组的大小是动态的。目前,我使用的是 Python,但我对任何需要使用的语言持开放态度。
我的目标
看到这个问题后:How to select specific item from cartesian product without calculating every other item,我认为这是一个了不起的算法,可以在给定索引的情况下生成一个集合。但是,这只适用于 3 个数组。我的最终目标是这样的,其中确定集合的函数是find_set:
Input:
A = [ A_0, A_1, A_2, ..., A_n ]
B = [ B_0, B_1, B_2, ..., B_n ]
C = [ C_0, C_1, C_2, ..., C_n ]
D = [ D_0, D_1, D_2, ..., D_n ]
...
N = [ N_0, N_1, D_2, ..., N_n ]
List = [ A, B, C, D, ... N]
find_set(List, 0) -> [ A_0, B_0, C_0, ..., N_0 ]
find_set(List, 1) -> [ A_0, B_0, C_0, ..., N_1 ]
...
对于任何给定的索引,依此类推。
到目前为止我做了什么
我使用 Python 2.7 和 itertools.product 来生成所有组合,但这只会生成一个迭代器。在遇到内存消耗问题后,我尝试了这样的事情:
results = itertools.product(*List)
# generates 100,000 random indices between 0 and the size of the Cartesian Product
desired_indices = random.sample(xrange(0, calculated_size - 1), 100000)
for item, index in results:
if index in desired_indices:
# do things
问题是,无论如何这都会导致 O(N) 操作,当我有 433,501,216 个可能的集合时,这将需要很长时间才能找到一个非常小的子集。感谢所有帮助和任何其他资源,我可以寻求更多关于该主题的知识。
【问题讨论】:
标签: python set itertools cartesian-product