简体   繁体   中英

Python eval expression all permutations for arithmetic operators

Given string = '1*7/5-3'

I have expression to evaluate the string like eval('1*7/5-3')

Code :

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

I want to evaluate for all permutations

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

I shouldn't have edited it to eliminate the "extraneous" parentheses. They were in fact, necessary. I'm reverting to the original code.

The idea is to consider each operator symbol in turn as the main operation -- the root of the binary expression tree . This splits the string into two parts, and we apply the procedure recursively.

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

This prints

(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

BTW is this for Euler Project problem 93?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM