[英]Running into 'MemoryError' when running this Python code
我知道我的代码可能包含很多冗余,但我真的很难优化它。
from itertools import permutations
n = 2
new = ['(',')'] * n
paren = list(permutations(new,(n*2)))
def matched(str):
count = 0
for i in str:
if i == "(":
count += 1
elif i == ")":
count -= 1
if count < 0:
return False
return count == 0
z = []
for d in paren:
true = ''.join(d)
if matched(true) == True:
z.append(d)
f2 = set(z)
r = []
for i in f2:
stru = ''.join(i)
r.append(stru)
print(r)
这个程序的目标是提供所有可能的 n 对平衡括号。 最终结果应该是一个包含各种字符串的列表,其中包含括号 Ex: for n = 2 [ '()()', '(())' ]。 不幸的是,此代码仅在 n < 6 时有效,否则程序会遇到 memory 问题。
文件“real.py”,第 4 行,paren = list(permutations(new,(n*2))) MemoryError
先感谢您!
您可以为此目的使用递归生成器:
def parens(s, max_len, n_open):
if len(s) + n_open == max_len:
yield s + n_open*')'
elif n_open == 0:
yield from parens(s + '(', max_len, n_open + 1)
else:
yield from parens(s + '(', max_len, n_open + 1)
yield from parens(s + ')', max_len, n_open - 1)
然后你可以像这样迭代结果:
n = 3
for s in parens('(', max_len=2*n, n_open=1):
print(s)
例如n=3
的 output:
((()))
(()())
(())()
()(())
()()()
让我们使用小n
实际诊断paren
的内容:
# As before...
from itertools import permutations
n = 2
new = ['(',')'] * n
paren = list(permutations(new,(n*2)))
def display(elements):
for item in elements:
print(''.join(item))
display(sorted(paren))
你会注意到相当多的重复。
但是itertools.combinations
也不能直接工作——所有元素只有一个唯一的组合,因为顺序是如何考虑的。
我们有多个相同的元素,我们希望它们的顺序很重要,但不是在相同的元素之间。
相反,诀窍是选择(
s 将 go (并将)
s 放在其他位置) 的位置。 为此,我们可以简单地对 position 个候选对象使用一个range(n*2)
,然后选择其中的n
combinations
。 然后只需构建相应的字符串即可。
(也许你可以想出一种方法来直接检查给定的(
positions 组合是否对应于匹配括号的有效字符串。提示:两个相邻(
positions 之间的区别告诉你)
s?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.