How to generate all valid permutations of parentheses in Python?

Question:

I want to generate all possible permutations of a set of parentheses of a certain length N.

Example:

if N = 1
Output: ['()']

if N = 3
Output: ['()(())', '(())()', '(()())', '((()))', '()()()']
Asked By: Fijaja Mulla

||

Answers:

Credit: https://prepinsta.com/python-program/generate-all-combinations-of-balanced-parentheses/

def generateParenthesis(n, Open, close, s, ans):

    if Open == n and close == n:
        ans.append(s)
        return

    if Open < n:
        generateParenthesis(n, Open + 1, close, s + "(", ans)

    if close < Open:
        generateParenthesis(n, Open, close + 1, s + ")", ans)


n = 3
ans = []
generateParenthesis(n, 0, 0, "", ans)
for s in ans:
    print(s)
Answered By: Yaser Sakkaf

As a fresher I came up with this solution where I create all the possible combinations using the function generate_permutations and then create a new list with only valid parentheses:

def generate_permutations(current, perms, prefix=''):
    if len(current) == 0:
        perms.add(prefix)

    for i in range(len(current)):
        new_prefix = prefix + current[i]
        new_current = current[:i] + current[i+1:]
        generate_permutations(new_current, perms, new_prefix)
    return perms


def refine(l):
    os = list()
    cs = list()
    res = list()
    for each in l:
        flag = True
        for e in each:
            if e == '(':
                os.append(e)
            elif e == ')':
                cs.append(e)
                if os and os[-1] == '(':
                    os = os[:-1]
                    cs = cs[:-1]
                else:
                    flag = False
                    break
        if flag:
            res.append(each)
    return res

    
N = 3
string = "()" * N
answer_list = generate_permutations(string, set())
refined = refine(answer_list)
print(refined)
Answered By: Fijaja Mulla
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.