代码之家  ›  专栏  ›  技术社区  ›  Ivan Shelonik

用运算符计算数字表[闭合]

  •  -3
  • Ivan Shelonik  · 技术社区  · 6 年前

    计算列表中的值有一个有趣的任务。

    [2025, 'minus', 5, 'plus', 3] 
    

    2023

    [2, 'multiply', 13]
    

    26

    对如何在python3中实现它有什么建议吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   mad_    6 年前

    按照@roganjosh的建议,创建一个dict并执行操作

    import operator
    ops = { "plus": operator.add, "minus": operator.sub,'multiply':operator.mul, 'divide':operator.div } 
    a=[2025, 'minus', 5, 'plus',3] 
    try:
        val=int(a[0])
        stack=[]
        error=False
    
        for i in range(1,len(a)):
            if isinstance(a[i],str):
                stack.append(a[i])
            if isinstance(a[i],int):
                temp_operator =stack.pop()
                operation=ops.get(temp_operator)
                val=operation(val,a[i])
    except Exception:
        print('Invalid input')
        error=True
    if(stack):
        print('Invalid input')
        error=True
    if(not error):
        print(val)
    

    2023
    
        2
  •  1
  •   vash_the_stampede    6 年前

    import operator
    
    string_operator = {
        "plus" : operator.add,
        "minus" : operator.sub,
        "multiply" : operator.mul,
        "divide" : operator.truediv}
    
    problem = [2025, "minus", 5, "plus", 3]
    
    for i in range(len(problem)):
        if problem[i] in string_operator.keys():
            problem[i] = string_operator[problem[i]]
            solution = problem[i](problem[i-1],problem[i +1])
            problem[i+1] = solution
    
    print(solution)
    

    输出

    (xenial)vash@localhost:~/python$ python3 helping.py  
    2023
    

    problem = [2, "multiply", 13] :

    (xenial)vash@localhost:~/python$ python3 helping.py 
    26
    

    评论

    这将遵循代码并按操作符的显示顺序处理操作符,不确定是否要遵循操作顺序,没有提及。

    truediv floordiv ).

    如果 problem 是运营商之一。然后将字符串转换为相应的运算符( problem[i] = string_operator[problem[i]] 它将采用之前的值( i-1 )以及( i+1

    ( solution = problem[i](problem[i-1], problem[i+1])

    为了继续计算,我将输出存储在所述操作符后面的项中( 我+1 ),通过设置,它将是下一个运算符之前的项,这将允许进程继续。

    problem = [26, "multiply", 100, "divide", 2, "plus", 40, "minus", 3]
    
    (xenial)vash@localhost:~/python$ python3 helping.py 
    1337
    

    :)