zoukankan      html  css  js  c++  java
  • python 计算器 -- 正则练习

    #!/usr/bin/python
    # -*- coding: utf-8 -*-

    import sys,logging,os
    import re

    计算: s = '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. 处理加法、减法

    def deal_sign(s):
    s = s.replace('--', '+')
    s = s.replace('++', '+')
    s = s.replace('+-', '-')
    return s

    def multi_div(s): #(3*6+9)
    while re.search('d+.?d*[*/]-?d+.?d*', s):
    s_temp = re.search('d+.?d*[*/]-?d+.?d*', s).group()
    if s_temp.count('*'):
    x,y = re.split('*',s_temp)
    result = float(x) * float(y)
    elif s_temp.count('/'):
    x,y = re.split('/',s_temp)
    result = float(x) / float(y)
    s = s.replace(s_temp, str(result))
    return s

    def plus_mines(s): # (1-9+1.2)
    while re.search('-?d+.?d*[-+]d+.?d*', s) :
    s_temp = re.search('-?d+.?d*[-+]d+.?d*', s).group()
    if re.search('d+.?d*+', s_temp):
    x,y = re.split('+',s_temp)
    result = float(x) + float(y)
    elif re.search('d+.?d*-', s_temp):
    if s_temp.startswith('-'):
    x, y = re.split('-', s_temp[1:])
    result = - float(x) - float(y)
    else:
    x, y = re.split('-', s_temp)
    result = float(x) - float(y)
    s = s.replace(s_temp, str(result))

    return s

    def count_reslut(source):
    if len(re.findall('[a-zA-Z]',source)) == 0 and len(re.findall('(', source)) == len(re.findall(')', source)):
    source_trim = source.replace(' ', '')
    while re.findall('(', source_trim):
    # str1 = re.search('([0-9.*+/-]+)',source_trim).group() ##
    str1 = re.search('([^()]+)',source_trim).group() ##
    source_temp = multi_div(str1)
    source_temp = plus_mines(source_temp)
    source_trim = source_trim.replace(str1, source_temp[1:-1])
    source_trim = deal_sign(source_trim)
    else:
    source_temp = multi_div(source_trim)
    source_temp = deal_sign(source_temp)
    source_temp = plus_mines(source_temp)
    source_trim = deal_sign(source_temp)
    return source_trim

    else:
    print("您输入的字符串不合法!")


    s = '1 + 32 + (3 + 9) * 5 + ( 1 +3-(3*6+9)*8 + 43 * 91 +9/3*(4+71))-10-(-1)'
    print(count_reslut(s))
    s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
    print(count_reslut(s))
    s='(1.5+1)'
    print(count_reslut(s))
  • 相关阅读:
    Spring优雅关闭之:ShutDownHook
    RocketMQ一直打印RocketmqRemoting closeChannel: close the connection to remote address[] result: true
    MVC中使用内建的HTML辅助方法产生表单元素提交表单与button按钮事件的陷阱
    js代码生成form,解决mvc的url参数过长问题
    jQuery中关于height,innerWidth与outerWidth的区别
    Chrome和Firefox浏览器执行new Date() 函数传参数得到不同结果的陷阱
    SQL时间段查询、分页、in字符串正则拆分
    JAVA初始化文件代码
    Base64加密URL、解密URL
    Spring XML model validation
  • 原文地址:https://www.cnblogs.com/livid/p/9627830.html
Copyright © 2011-2022 走看看