【发布时间】:2020-03-14 16:22:58
【问题描述】:
给定一个二维矩阵,例如[[a,b,c],[d,e,f]...]],我想对该矩阵进行笛卡尔积,以便确定所有可能的组合。
对于这个特定的约束,当我使用具有 12 个不同子集的二维矩阵时,它使用的内存超过了我所拥有的 16 兆字节的分配内存。每个子集中有三个值,所以我会有 312 种不同的组合。
我使用的笛卡尔积函数是:
def cartesian_iterative(pools):
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
return result
我想知道如何在不使用任何外部库的情况下减少内存消耗。我将使用的示例二维数组是[['G', 'H', 'I'], ['M', 'N', 'O'], ['D', 'E', 'F'], ['D', 'E', 'F'], ['P', 'R', 'S'], ['D', 'E', 'F'], ['M', 'N', 'O'], ['D', 'E', 'F'], ['D', 'E', 'F'], ['M', 'N', 'O'], ['A', 'B', 'C'], ['D', 'E', 'F']]
编辑: 作为参考,可以在此处找到问题陈述的链接Problem Statement。这是可能名称文件的链接Acceptable Names。
最终代码:
with open('namenum.in','r') as fin:
num = str(fin.readline().strip()) #the number being used to determine all combinations
numCount = []
for i in range(len(num)):
numCount.append(dicti[num[i]]) #creates a 2d array where each number in the initial 'num' has a group of three letters
def cartesian_iterative(pools): #returns the product of a 2d array
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
return result
pos = set() #set of possible names
if len(num) == 12: #only uses more than the allocated memory when the num is 12 digits long.
'''
This optimization allows the product to only calculate 2 * 3^6 values, instead of 3**12. This saves a lot of memory
'''
rights = cartesian_iterative(numCount[6:])
for left in cartesian_iterative(numCount[:6]):
for right in rights:
a = ''.join(left+right)
if a in names:
pos.add(a) #adding name to set
else: #if len(num) < 12, you do not need any other optimizations and can just return normal product
for i in cartesian_iterative(numCount):
a = ''.join(i)
if a in names:
pos.add(a)
pos = sorted(pos)
with open('namenum.out','w') as fout: #outputting all possible names
if len(pos) > 0:
for i in pos:
fout.write(i)
fout.write('\n')
else:
fout.write('NONE\n')
【问题讨论】:
-
似乎
itertools.product是解决问题的最佳选择。它返回一个生成器,因此它是内存友好的。您知道/尝试过吗? -
我知道模块/功能,但我希望可以在不使用库的情况下进行优化。
-
itertools是一个内置库。它经过验证、快速且众所周知(可读)。你为什么不想使用它? -
是的,我认为这个问题的答案是“使用
itertools.product,如果你出于某种原因不想使用它,复制它的C源代码并编写一个扩展”。跨度> -
@ggorlen 我猜
itertools.product是代码came from...
标签: python optimization memory cartesian