Python:遍历表达式上的平衡括号

Python: Iterate through balanced parentheses on an expression

我找到了一些代码 :

from itertools import product
import numpy as np

operands = np.array(['a', 'b', 'c', 'd', 'e'])
operators = np.array([ '&', '|'])

for opers in product(operators, repeat=len(operands)-1):

    formula = [ str(operands[0]) ]

    for op, operand in zip(opers, operands[1:]):
        formula.extend([op, str(operand)])

    formula = ' '.join(formula)    
    print(formula)

我稍微修改了 link 的代码,我的代码(上面)输出:

a & b & c & d & e
a & b & c & d | e
a & b & c | d & e
a & b & c | d | e
a & b | c & d & e
a & b | c & d | e
a & b | c | d & e
a & b | c | d | e
a | b & c & d & e
a | b & c & d | e
a | b & c | d & e
a | b & c | d | e
a | b | c & d & e
a | b | c & d | e
a | b | c | d & e
a | b | c | d | e

对于此输出中的每个表达式,我想遍历并打印平衡括号的每个可能组合。

例如,对于第一个表达式,我们将得到:

(a & b) & c & d & e
((a & b) & c) & d & e
(a & (b & c)) & d & e
((a & b) & c & d) & e
((a & b) & (c & d)) & e
((a & b & c) & d) & e
(((a & b) & c) & d) & e
((a & (b & c)) & d) & e
...

我该怎么做(同时将执行时间保持在最低限度)?

奖金:Remove/prevent 任何重复项

我看到有一个类似的问题 here,但是 question/answers 不在输出表达式中包含运算符。

我最终使用了这里的答案:

def parenthesized (exprs):
    if len(exprs) == 1:
        yield exprs[0]
    else:
        first_exprs = []
        last_exprs = list(exprs)
        while 1 < len(last_exprs):
            first_exprs.append(last_exprs.pop(0))
            for x in parenthesized(first_exprs):
                if 1 < len(first_exprs):
                    x = '(%s)' % x
                for y in parenthesized(last_exprs):
                    if 1 < len(last_exprs):
                        y = '(%s)' % y
                    yield '%s%s' % (x, y)

for x in parenthesized(['a', 'b', 'c', 'd']):
    print x