Python eval表达式算术运算符的所有排列

时间:2015-10-20 02:56:45

标签: python eval combinations permutation

给定string = '1*7/5-3'

我有表达式来评估像eval('1*7/5-3')

这样的字符串

代码:

import __future__
string = '1*7/5-3'
print eval(compile(string, '<string>', 'eval', __future__.division.compiler_flag))

我想评估所有排列

example 
        eval('((1*7)/5)-3') 
        eval('1*((7/5)-3)')
        and so on

1 个答案:

答案 0 :(得分:0)

我不应该编辑它以消除&#34;无关的&#34;括弧。事实上,他们是必要的。我将恢复原始代码。

我们的想法是将每个运算符符号依次视为主要操作 - binary expression tree的根。这将字符串分成两部分,我们以递归方式应用该过程。

 def parenthesize(string):
    '''
    Return a list of all ways to completely parenthesize operator/operand string
    '''
    operators = ['+','-','*','/']
    depth = len([s for s in string if s in operators]) 
    if depth == 0:
        return [string]
    if depth== 1:
        return ['('+ string + ')']
    answer = []
    for index, symbol in enumerate(string):
        if symbol in operators:
            left = string[:index]
            right = string[(index+1):]
            strings = ['(' + lt + ')' + symbol +'(' + rt + ')' 
                           for lt in parenthesize(left) 
                           for rt in parenthesize(right) ]
            answer.extend(strings)
    return answer    

 string='4+7/5-3'
 for t in parenthesize(string):print(t, eval(t))

打印

(4)+((7)/((5-3))) 7.5
(4)+(((7/5))-(3)) 2.4
((4+7))/((5-3)) 5.5
((4)+((7/5)))-(3) 2.4000000000000004
(((4+7))/(5))-(3) -0.7999999999999998
对于欧拉项目问题93,BTW是这个吗?