I understand my code probably contains quite a few redundancies but I'm really struggling with optimizing it.
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)
My objective with this program is to provide with all possible n pairs of balanced parenthesis. The final results should be a list with various strings containing the parenthesis Ex: for n = 2 [ '()()', '(())' ]. Unfortunately this code only works when n < 6, otherwise the program runs into a memory issue.
File "real.py", line 4, in paren = list(permutations(new,(n*2))) MemoryError
Thank you in advance!
n == 6. How many elements do you expect to be in the resultingparen? Show your reasoning. Now, how much memory do you expect that to take up? Are you surprised that your machine can't handle that?permutationsinto a list, forcing every single one to be stored in memory whether valid or not. It makes much more sense to iterate over it directly, consuming no memory unless a given entry passes thematchedtest. An even better solution would be to generate the valid strings directly, without first generating all permutations and then filtering them.combinationsrather thanpermutations. This is really a math question rather than a programming question, although reading the documentation also helps.