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

问题描述

我找到了一些 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)

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

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

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

奖励:删除/防止任何重复

我看到有一个类似的问题 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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...