python中的计算器 [英] Calculator in python

查看:67
本文介绍了python中的计算器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个可以使用基本4个运算符来求解表达式的计算器,例如1 + 2 * 3-4 / 5,但是它不起作用,我也不知道出了什么问题。请检查我的代码。
运行它时,我在8中得到无限个错误。line return ret(parts [0])* ret(parts [2])
这是代码

I am trying to make calculator that can solve expressions with basic 4 operators, like 1+2*3-4/5, however it does not work and I do not know what is wrong. Please check my code. When I run it, I am getting infinte number of errors in 8. line return ret(parts[0]) * ret(parts[2]) Here is code

def ret(s):
    s = str(s)
    if s.isdigit():
        return float(s)
    for c in ('*','/','+','-'):
        parts = s.partition(c)
        if c == '*':
            return ret(parts[0]) * ret(parts[2])
        elif c == '/':
            return ret(parts[0]) / ret(parts[2])
        elif c == '+':
            return ret(parts[0]) + ret(parts[2])
        elif c == '-':
            return ret(parts[0]) - ret(parts[2])
print(ret('1+2'))

错误回溯结束于:

  File "C:\Python33\calc.py", line 8, in ret
    return ret(parts[0]) * ret(parts[2])
  File "C:\Python33\calc.py", line 2, in ret
    s = str(s)
RuntimeError: maximum recursion depth exceeded while calling a Python object


推荐答案

无论如何,都对输入字符串进行分区,从不检查如果操作员在那里 .partition()如果输入中不存在分区字符,则返回空字符串:

You partition the input string regardless, never checking if the operator is even there. .partition() returns empty strings if the partition character is not present in the input:

 >>> '1+1'.partition('*')
 ('1+1', '', '')

所以您将调用 s.partition('*'),但不要检查是否有 这样的运算符当前,导致无条件调用 ret()。您将始终调用 ret(parts [0])* ret(parts [2]),而不管 * 是否出现在 s 中。

So you'll call s.partition('*') but never check if there is any such operator present, resulting in unconditional calls to ret(). You'll always call ret(parts[0]) * ret(parts[2]) regardless of wether * is present in s or not.

解决方案是测试运算符 first 或检查 .partition()的返回值。后者可能是最简单的:

The solution is to either test for the operator first or to check the return value of .partition(). The latter is probably easiest:

for c in ('+','-','*','/'):
    parts = s.partition(c)
    if parts[1] == '*':
        return ret(parts[0]) * ret(parts[2])
    elif parts[1] == '/':
        return ret(parts[0]) / ret(parts[2])
    elif parts[1] == '+':
        return ret(parts[0]) + ret(parts[2])
    elif parts[1] == '-':
        return ret(parts[0]) - ret(parts[2])

请注意,我颠倒了操作员订单;是的,在加法和减法之前需要应用乘法和除法,但是您正在此处进行 reverse ;将表达式拆分为较小的部分,然后在处理子表达式后应用操作。

Note that I reversed the operator order; yes, multiplication and division need to be applied before addition and subtraction, but you are working in reverse here; splitting up the expression into smaller parts, and the operations are then applied when the sub-expression has been processed.

您可以使用赋值拆包来赋值3的返回值。 .partition()以更简单的名称:

You could use assignment unpacking to assign the 3 return values of .partition() to easier names:

for c in ('+','-','*','/'):
    left, operator, right = s.partition(c)
    if operator == '*':
        return ret(left) * ret(right)
    elif operator == '/':
        return ret(left) / ret(right)
    elif operator == '+':
        return ret(left) + ret(right)
    elif operator == '-':
        return ret(left) - ret(right)

接下来,您可以使用 operator 模块,其功能与算术运算的功能相同。地图应该执行以下操作:

Next you can simplify all this by using the operator module, which has functions that perform the same operations as your arithmetic operations. A map should do:

import operator
ops = {'*': operator.mul, '/': operator.div, '+': operator.add, '-': operator.sub}

for c in ('+','-','*','/'):
    left, operator, right = s.partition(c)
    if operator in ops:
        return ops[operator](ret(left), ret(right))

这篇关于python中的计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆