zoukankan      html  css  js  c++  java
  • 模拟计算器

    题目:

    模拟计算器开发:

    实现加减乘除及拓号优先级解析

    用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等类似公式后,必须自己解析里面的(),+,-,*,/符号和公式(不能调用eval等类似功能偷懒实现),运算后得出结果,结果必须与真实的计算器所得出的结果一致

    流程图:

    代码:

    #!/usr/bin/env python
    # -*-coding:utf-8-*-
    # _author_=zh
    import re
    
    a='1 - 2 * ((60 - 30 + (-40 / 5) * (9 - 2 * 5 / 3 + 7 / 3 * 99 / 4 * 2998 + 10 * 568 / 14)) - (-4 * 3) / (16 - 3 * 2))'
    a="("+a+")"
    
    #找最里层括号
    while re.search("([^()]*)", a):
        z1=re.search("([^()]*)", a).group()
        save=z1
        # 处理括号内部乘除
        while re.search('d+.?d*s*[/*]s*[+-]?d+.?d*', z1):
            z2 = re.search('d+.?d*s*[/*]s*[+-]?d+.?d*', z1).group()
            # 分割
            z3 = re.findall('d+.?d*|[-/*]', z2)
            if "-" in z3:
                z3.remove("-")
            if "/" in z3:
                z4 = float(z3[0]) / float(z3[2])
            else:
                z4 = float(z3[0]) * float(z3[2])
            z4=z4 if "-" not in z2 else -z4
            z1 = z1.replace(z2, str(z4))
        # 处理括号内部加减
        while re.search('d+.?d*s*[+-]s*[+-]*s*d+.?d*', z1):
            s2 = re.search('d+.?d*s*[+-]s*[+-]*s*d+.?d*', z1).group()
            s3 = re.findall('d+.?d*|[+-]', s2)
            #当出现++的情况时
            if s3.count("+") == 2:
                s3.remove("+")
            elif s3.count("-") == 2:
                s3.remove("-")
                s3[1] = "+"
            elif s3.count("+")==1 and s3.count("-")==1:
                s3.remove("+")
            if "+" in s3:
                s4 = float(s3[0]) + float(s3[2])
            else:
                s4 = float(s3[0]) - float(s3[2])
            z1 = z1.replace(s2, str(s4))
        #运算完成去除括号
        z1=z1.strip("(").strip(")")
        a=a.replace(save,str(z1))
    print(a)
  • 相关阅读:
    Leetcode Binary Tree Preorder Traversal
    Leetcode Minimum Depth of Binary Tree
    Leetcode 148. Sort List
    Leetcode 61. Rotate List
    Leetcode 86. Partition List
    Leetcode 21. Merge Two Sorted Lists
    Leetcode 143. Reorder List
    J2EE项目应用开发过程中的易错点
    JNDI初认识
    奔腾的代码
  • 原文地址:https://www.cnblogs.com/zh-20170913/p/7612320.html
Copyright © 2011-2022 走看看