微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。