教学项目之-通过Python实现简单的计算器

 

计算器开发需求

  1. 实现加减乘除及拓号优先级解析
  2. 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等类似公式后,必须自己解析里面的(),+,-,*,/符号和公式,运算后得出结果,结果必须与真实的计算器所得出的结果一致
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import re
import functools
 
 
def minus_operator_handler(formula):
    '''处理一些特殊的减号运算'''
    minus_operators = re.split("-",formula)
    calc_list= re.findall("[0-9]",formula)
    if minus_operators[0== '': #第一值肯定是负号
        calc_list[0= '-%s' % calc_list[0]
    res = functools.reduce(lambda x,y:float(x) - float(y), calc_list)
    print("\033[33;1m减号[%s]处理结果:\033[0m" % formula, res )
    return res
 
def remove_duplicates(formula):
    formula = formula.replace("++","+")
    formula = formula.replace("+-","-")
    formula = formula.replace("-+","-")
    formula = formula.replace("--","+")
    formula = formula.replace("- -","+")
    return formula
def compute_mutiply_and_dividend(formula):
    '''算乘除,传进来的是字符串噢'''
    operators = re.findall("[*/]", formula )
    calc_list = re.split("[*/]", formula )
    res = None
    for index,i in enumerate(calc_list):
        if res:
            if operators[index-1== "*":
                res *= float(i)
            elif operators[index-1== "/":
                res /= float(i)
        else:
            res = float(i)
 
    print("\033[31;1m[%s]运算结果=\033[0m" %formula, res  )
    return res
def handle_minus_in_list(operator_list,calc_list):
    '''有的时候把算术符和值分开后,会出现这种情况  ['-', '-', '-'] [' ', '14969037.996825399 ', ' ', '12.0/ 10.0 ']
       这需要把第2个列表中的空格都变成负号并与其后面的值拼起来,恶心死了
    '''
    for index,i in enumerate(calc_list):
        if == '': #它其实是代表负号,改成负号
            calc_list[index+1= + calc_list[index+1].strip()
def handle_special_occactions(plus_and_minus_operators,multiply_and_dividend):
    '''有时会出现这种情况 , ['-', '-'] ['1 ', ' 2 * ', '14969036.7968254'],2*...后面这段实际是 2*-14969036.7968254,需要特别处理下,太恶心了'''
    for index,i in enumerate(multiply_and_dividend):
        = i.strip()
        if i.endswith("*"or i.endswith("/"):
            multiply_and_dividend[index] = multiply_and_dividend[index] + plus_and_minus_operators[index] + multiply_and_dividend[index+1]
            del multiply_and_dividend[index+1]
            del plus_and_minus_operators[index]
    return plus_and_minus_operators,multiply_and_dividend
def compute(formula):
    '''这里计算是的不带括号的公式'''
 
    formula = formula.strip("()"#去除外面包的拓号
    formula = remove_duplicates(formula) #去除外重复的+-号
    plus_and_minus_operators = re.findall("[+-]", formula)
    multiply_and_dividend = re.split("[+-]", formula) #取出乘除公式
    if len(multiply_and_dividend[0].strip()) == 0:#代表这肯定是个减号
        multiply_and_dividend[1= plus_and_minus_operators[0+ multiply_and_dividend[1]
        del multiply_and_dividend[0]
        del plus_and_minus_operators[0]
 
    plus_and_minus_operators,multiply_and_dividend=handle_special_occactions(plus_and_minus_operators,multiply_and_dividend)
    for index,i in enumerate(multiply_and_dividend):
        if re.search("[*/]" ,i):
            sub_res = compute_mutiply_and_dividend(i)
            multiply_and_dividend[index] = sub_res
 
    #开始运算+,-
    print(multiply_and_dividend, plus_and_minus_operators)
    total_res = None
    for index,item in enumerate(multiply_and_dividend):
        if total_res: #代表不是第一次循环
            if plus_and_minus_operators[index-1== '+':
                total_res += float(item)
            elif plus_and_minus_operators[index-1== '-':
                total_res -= float(item)
        else:
            total_res = float(item)
    print("\033[32;1m[%s]运算结果:\033[0m" %formula,total_res)
    return total_res
 
def calc(formula):
    '''计算程序主入口, 主要逻辑是先计算拓号里的值,算出来后再算乘除,再算加减'''
    parenthesise_flag = True
    calc_res = None #初始化运算结果为None,还没开始运算呢,当然为None啦
    while parenthesise_flag:
        = re.search("\([^()]*\)", formula) #找到最里层的拓号
        if m:
            #print("先算拓号里的值:",m.group())
            sub_res = compute(m.group())
            formula = formula.replace(m.group(),str(sub_res))
        else:
            print('\033[41;1m----没拓号了...---\033[0m')
 
            print('\n\n\033[42;1m最终结果:\033[0m',compute(formula))
            parenthesise_flag = False #代表公式里的拓号已经都被剥除啦
 
if __name__ == '__main__':
 
    #res = calc("1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )")
    res = calc("1 - 2 * ( (60-30 +(-9-2-5-2*3-5/3-40*4/2-3/5+6*3) * (-9-2-5-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )")

  

 
 
好文要顶 关注我 收藏该文  
0
0
 
 
 
posted @ 2016-01-29 19:17 金角大王 阅读(1035) 评论(0)  编辑 收藏
 
 

教学项目之-通过Python实现简单的计算器的更多相关文章

  1. python实现简单的计算器功能

    如想实现一个计算器的功能,输入格式为字符串,不能运用python里面的内置方法,出去简单的加减乘除,设计一个相对高级的计算器: a = '1 - 2 * ( ( 6 0 -3 0 +(-40/5) * ...

  2. 用python实现简单的计算器(加减乘除小括号等)

    需求:实现能计算类似 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) ...

  3. 在大型项目上,Python 是个烂语言吗

    Robert Love, Google Software Engineer and Manager on Web Search. Upvoted by Kah Seng Tay, I was the ...

  4. Python实现简单的四则运算

    GitHub 项目地址 https://github.com/745421831/-/tree/master PSP PSP2.1 Personal Software Process Stages 预 ...

  5. python 的排名,已经python的简单介绍

    我在今天看了一篇文章,是简书的全网程序猿写的,Java已经退出神坛,python稳居第一. python是由龟叔写的,它在英文的意思是蟒蛇. 根据编程语言流行指数排行榜2019年2月的榜单 据了解,目 ...

  6. python scrapy简单爬虫记录(实现简单爬取知乎)

    之前写了个scrapy的学习记录,只是简单的介绍了下scrapy的一些内容,并没有实际的例子,现在开始记录例子 使用的环境是python2.7, scrapy1.2.0 首先创建项目 在要建立项目的目 ...

  7. python创建简单网站

    前言 本方法基于web2py框架,使用web2py的完整网站数据包创建简单网站. web2py 是一个为Python语言提供的全功能Web应用框架,旨在敏捷快速的开发Web应用,具有快速.安全以及可移 ...

  8. Python爬虫简单实现CSDN博客文章标题列表

    Python爬虫简单实现CSDN博客文章标题列表 操作步骤: 分析接口,怎么获取数据? 模拟接口,尝试提取数据 封装接口函数,实现函数调用. 1.分析接口 打开Chrome浏览器,开启开发者工具(F1 ...

  9. Python 实现简单的 Web

    简单的学了下Python, 然后用Python实现简单的Web. 因为正在学习计算机网络,所以通过编程来加强自己对于Http协议和Web服务器的理解,也理解下如何实现Web服务请求.响应.错误处理以及 ...

随机推荐

  1. YII 小部件 解决多选按钮和单选按钮不在同一水平上 'separator'=>' '

    主要是添加separator属性(这里)$hoddy,$sex在控制器里面定义的数组,然后render传过来的 <td>          <?php echo $form-> ...

  2. CSS lib

    Yahoo的轻型CSS框架Pure来加速web开发 http://purecss.io/buttons/#

  3. VIM快捷键(转)

    VIM快捷键:光标移动:四个方向   kh 0 l   j  ctrl+f, ctrl+b                 向下翻页,向上翻页  ctrl+d, ctrl+u              ...

  4. jQuery运维开发之第十七天

    JQuery 学习参考网址http://jquery.cuishifeng.cn/ python中叫模块,在DOM/BOM/Javascript中叫类库 现在的JQ版本有:1.x 2.x 3.x 建议 ...

  5. HDU2602 (0-1背包问题)

      N - 01背包 Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u   Descri ...

  6. 练习2 A - ASCII码排序

      Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u   Description 输入三 ...

  7. Mvc Controller 单元测试 Mock User.Identity.Name

    被测试的Action 包含 User.Identity.Name 代码,在写测试代码需要Mock ControllerContext对象 代码如下: var mock = new Mock<Co ...

  8. 转:Github上最受关注的前端大牛,快来膜拜吧!

    原文来自于:http://code.csdn.net/news/2820990 本文列出了Github上最受关注的10位前端大牛.看看他们负责的项目和提交的代码,你是不是能从中学到些什么? 1. Pa ...

  9. 【HDOJ】3442 Three Kingdoms

    bfs+状态压缩.初始化数组的曼哈顿距离条件写错了,改了一下午. /* 3442 */ #include <iostream> #include <cstdio> #inclu ...

  10. 【Linux】鸟哥的Linux私房菜基础学习篇整理(二)

    1. dumpe2fs [-bh] devicename:查询superblock信息.参数:-b:列出保留为坏道的部分:-h:列出superblock的数据,不会列出其他的区段内容. 2. df [ ...