首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >基本算术计算器

基本算术计算器
EN

Code Review用户
提问于 2015-04-23 05:50:55
回答 1查看 2K关注 0票数 6

计算器支持基本运算符(Add,Substract,除法,乘)。

此刻,

  • 它只适用于正整数。
  • 我不验证我的用户输入。
  • 如果我的除法不是整数

这是一项正在进行的工作。这是我的第一个Python应用程序,所以我想在继续工作之前获得反馈。

下面是我的计算器如何解析/处理一个方程的一个例子:

给予3+3+9/3-4*2

  • 计算乘法: 3+3+9/3-8 (注4*2现在为8)
  • 然后分组表决: 3+3+3-8 (9/3 = 3)
  • 然后加法: 9-8 (3+3+3 = 9)
  • 最后减法:1 (9-8 = 1)
代码语言:javascript
运行
复制
import operator

priorizedOperators = operator.getPriorizedOperators()

def calculate(args):
    return _calculate(args,0)

def _calculate(equation, operatorArrayIndex):

    if len(priorizedOperators) == operatorArrayIndex:
        return equation;

    arithmeticOperator = priorizedOperators[operatorArrayIndex]
    copiedEquation = equation

    try:
        operatorLocation = copiedEquation.index(arithmeticOperator.getStringSign())

        while True:
            leftBound = _findLeftBound(equation,operatorLocation)
            rightBound = _findRightBound(equation,operatorLocation)

            leftValue = int(copiedEquation[leftBound:operatorLocation])
            rightValue = int(copiedEquation[operatorLocation+1:rightBound])

            temp = arithmeticOperator.operate(leftValue,rightValue)

            #Replaces the part of the equation we just computed by the result
            copiedEquation = copiedEquation[:leftBound] + str(temp) + copiedEquation[rightBound:]

            #This will throw an exception if index doesn't find the operator, which ends the while loop
            operatorLocation = copiedEquation.index(arithmeticOperator.getStringSign())
    finally:
        return _calculate(copiedEquation, operatorArrayIndex + 1)

def _findLeftBound(equation ,operatorIndex):
    for leftBoundSearchIndex in reversed(range(0,operatorIndex)):
        if not _isNumber(equation[leftBoundSearchIndex]):
            return leftBoundSearchIndex + 1

    return 0

def _findRightBound(equation, operatorIndex):
    for rightBoundSearchIndex in range(operatorIndex+1, len(equation)):
        if not _isNumber(equation[rightBoundSearchIndex]):
            return rightBoundSearchIndex

    return len(equation)

def _isNumber(char):
    return ord("0") <= ord(char) <= ord("9")

def main():
    equation = input("Enter equation : ")
    print(calculate(equation))

if __name__ == "__main__": main()

operator.py的内容

代码语言:javascript
运行
复制
class PlusOperator():
    def getStringSign(self):
        return "+"

    def operate(self,left,right):
        return left + right

class MinusOperator():
    def getStringSign(self):
        return "-"

    def operate(self,left,right):
        return left - right

class MultiplyOperator():
    def getStringSign(self):
        return "*"

    def operate(self,left,right):
        return left * right

class DivideOperator():
    def getStringSign(self):
        return "/"

    def operate(self,left,right):
        return left // right

def getPriorizedOperators():
    return [MultiplyOperator(),DivideOperator(),PlusOperator(),MinusOperator()]

我想知道我的python是否还好,我的算法是否合理。

EN

回答 1

Code Review用户

回答已采纳

发布于 2015-04-23 08:36:51

以下是一些简短的评论:

  • 阅读PEP 8风格指南。特别是,Python使用lowercase_with_underscore变量名,并在空格后面加上逗号。
  • 向函数中添加一些文档字符串,这样就可以清楚地知道它们在计算器上下文中的作用。当您扩展计算器时,这将变得非常有用,并且您希望更改现有的函数:您可能还记得每个函数目前的用途,但在六个月内可能不会。
  • 添加更多的评论。告诉我你为什么要做某些手术。任何人都可以阅读代码并看到它在做什么,但它为什么要这样做呢?例如:经过一些检查,我看到您在prioritizedOperators中迭代,按顺序应用每个操作(乘法和除法,然后减法和加法)。
  • 您没有错误处理,这意味着我可以输入像1/0这样愚蠢的内容并获得一个ZeroDivisionError。您还声称它只适用于正整数,但是我用负整数尝试的简单示例似乎也有效。如果你只想让它与正整数一起工作,那么你应该把任何不是正整数的输入都拿出来。
  • 如果我的除法不是整数的话,你可以说它是整数,但这似乎不是真的。例如,如果输入2/3,则得到输出0
  • getPriorizedOperators不需要是一个函数。只需在operator.py中将列表声明为变量,然后在calculator.py中导入它。例如: operator.py: prioritized_operators = 相乘_操作符(),除法_运算符()+_运算符(),减_运算符() calculator.py: from operator import prioritized_operators
  • 我会重命名你的_isNumber()函数。它只检查单个字符是否是数字,但名称意味着我可能能够传递任意长度的字符串。也许_is_digit()会更好。您可以稍微整理一下函数逻辑。您也可以直接比较字符串以获得相同的结果,而不是调用ord()。例如:>>> "0“< "5”< "9“真>>> "0”< "x“< "9”False,或者您可以只使用内置函数isdigit(),并完全取消您的函数:>>> "5".isdigit() True >>> "x".isdigit() False (是否使用后者取决于您希望重新创建车轮的程度)。
  • 有两个名为calculate()_calculate()的函数很容易混淆。将其中一个或两个重命名为具有更特定的名称。
票数 6
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/87717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档