【问题标题】:Python eval expression all permutations for arithmetic operatorsPython eval 表达式算术运算符的所有排列
【发布时间】:2015-10-20 02:56:44
【问题描述】:

给定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

【问题讨论】:

  • 尝试创建数值列表和操作列表。尝试创建一个函数,该函数在以指定顺序评估操作时返回结果: my_eval(list_values, list_ops, order_ops) 其中您的 order_ops=[1,2,3] 是您的第一个示例,而 order_ops=[2,3,1 ] 是你给出的第二个例子。似乎是递归的好候选

标签: python eval combinations permutation


【解决方案1】:

我不应该编辑它来消除“无关的”括号。事实上,它们是必要的。我正在恢复到原始代码。

这个想法是将每个运算符符号依次视为主要操作——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 题吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 2019-05-29
    • 2020-07-13
    • 1970-01-01
    • 2013-11-28
    相关资源
    最近更新 更多