pythonalgorithmnumpypython-itertoolscatalan

Python: Iterate through balanced parentheses on an expression


I found some code to iterate through arithmetic operators across a static, excecutable formula in Python:

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)

I modified the code from the link slightly, my code (above) outputs:

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

For each expression in this output, I would like to iterate through and print every possible combination of balanced parentheses.

For example, for the first expression we would get:

(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
...

How might I go about doing this (while keeping execution time to a minimum)?

Bonus: Remove/prevent any duplicates

I see there was a similar question here, but the question/answers do not include operators in the output expressions.


Solution

  • I ended up using the answer here:

    https://stackoverflow.com/a/6447533/12814841

    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