• Python 简单实现数学四则运算


    GitHub地址:https://github.com/compassblog/PythonExercise

    一、题目描述

    (1)能自动生成小学四则运算题目;

    (2)能支持真分数的四则运算;

    二、实现环境

    PyCharm、Python3.0

    三、代码实现

    import re
    
    def myCalculate(mystr):
        if (mystr.__contains__("(")):
            start = mystr.rindex("(")
            lstr = mystr[0:start]
            tmpstr = mystr[start + 1:]
            end = tmpstr.index(")")
            rstr = tmpstr[end + 1:]
            nowstr = tmpstr[0:end]
            newstr = lstr + str(myCalculate(nowstr)) + rstr
            return myCalculate(newstr)
        else:
            return calcNoSym(mystr)
    
    
    def calcNoSym(string):
        if (string.__contains__("*")):
            string = getNewStr(string, "*")
            return calcNoSym(string)
        if (string.__contains__("/")):
            string = getNewStr(string, "/")
            return calcNoSym(string)
        if (string.__contains__("+")):
            string = getNewStr(string, "+")
            return calcNoSym(string)
        if (string.__contains__("-")):
            string = getNewStr(string, "-")
            return calcNoSym(string)
        return string
    
    
    def getNewStr(string, op):
        start = string.index(op)
        lstr = string[0:start]
        rstr = string[start + 1:]
        lnum = re.search('d+$', lstr).group()
        rnum = re.search('d+', rstr).group()
        newstr = lstr.rstrip(lnum) + str(calcs(lnum, rnum, op)) + rstr.lstrip(rnum)
        return newstr
    
    
    def calcs(num1, num2, op):
        if (op == "+"):
            return int(num1) + int(num2)
        elif (op == "-"):
            return int(num1) - int(num2)
        elif (op == "*"):
            return int(num1) * int(num2)
        elif (op == "/"):
            return int(num1) / int(num2)
        else:
            raise "error"
    
    
    string = "11*22*3/4"
    
    print(myCalculate(string))
    sexp = "512+((112+212)*2-312)"
    print(myCalculate(sexp))

    四、结果测试

    1、加法测试

    2、减法测试

    3、乘法测试

    4、除法测试

    五、PSP表格

    扫码关注微信公众号,了解更多

  • 相关阅读:
    D触发器深入详细介绍(zhuanzai)
    脉冲
    数字电路中时序
    嵌入式中对某一位清0或置1
    8本推荐阅读的UX书籍
    Hadoop之HDFS的Shell操作
    Hadoop之HDFS概述
    Hadoop之搭建完全分布式运行模式
    Hadoop之运行模式
    Hadoop之运行环境搭建
  • 原文地址:https://www.cnblogs.com/compassblog/p/8883413.html
Copyright © 2020-2023  润新知