美文网首页
Python计算器之正则表达式实现

Python计算器之正则表达式实现

作者: Techml | 来源:发表于2017-05-02 08:50 被阅读0次
# -*- coding: utf-8 -*-

import re

Parentheses = re.compile(r'\([^()]*\)')  # find out the expression with parentheses but no parentheses inside
Mul_Dev = re.compile(r'(\d+\.?\d*)[*/]([+-]?\d+\.?\d*)')  # find out the expression with '*' or '/' only
Add_Sub = re.compile(r'(\d+\.?\d*)[+-](\d+\.?\d*)')  # find out the expression with '+' or '-' only


def compute_mul_dev(arg):
    """
    calculate the subexpression which has '*' or '/'
    """
    exp = Mul_Dev.search(arg[0])
    if not exp:
        return
    else:
        sub_exp = exp.group()

        if len(sub_exp.split('*')) > 1:
            n1, n2 = sub_exp.split('*')
            ret = str(float(n1) * float(n2))

        elif len(sub_exp.split('/')) > 1:
            n1, n2 = sub_exp.split('/')
            ret = str(float(n1) / float(n2))

        arg[0] = Mul_Dev.sub(ret, arg[0], 1)
        compute_mul_dev(arg)


def compute_add_sub(arg):
    """
    calculate the expression only has '+' or '-'
    """

    while True:
        if arg[0].__contains__('--') \
                or arg[0].__contains__('+-') \
                or arg[0].__contains__('-+') \
                or arg[0].__contains__('++'):
            arg[0] = arg[0].replace('--', '+')
            arg[0] = arg[0].replace('-+', '-')
            arg[0] = arg[0].replace('+-', '-')
            arg[0] = arg[0].replace('++', '+')
        else:
            break

    if arg[0].startswith('-'):
        arg[1] += 1
        arg[0] = arg[0].replace('-', '&')
        arg[0] = arg[0].replace('+', '-')
        arg[0] = arg[0].replace('&', '+')
        arg[0] = arg[0][1:]

    exp = Add_Sub.search(arg[0])

    if not exp:
        return

    sub_exp = exp.group()
    
    if len(sub_exp.split('+')) > 1:
        n1, n2 = sub_exp.split('+')
        ret = float(n1) + float(n2)
    elif len(sub_exp.split('-')) > 1:
        n1, n2 = sub_exp.split('-')
        ret = float(n1) - float(n2)
    arg[0] = Add_Sub.sub(str(ret), arg[0], 1)
    compute_add_sub(arg)


def compute(expression):
    """
    calculate the expression not has parentheses
    """
    exp = [expression, 0]
    compute_mul_dev(exp)
    compute_add_sub(exp)
    cnt = divmod(exp[1], 2)
    result = float(exp[0])
    if (cnt[1] == 1):
        result = -1 * result
    return result


def execute(expression):
    """
    calculate the expression in parentheses
    """
    
    if not Parentheses.search(expression):
        return expression

    sub_exp = Parentheses.search(expression).group()
    compute_exp = sub_exp[1:-1]
    ret = compute(compute_exp)
    new_exp = Parentheses.sub(str(ret), expression, 1)
    return execute(new_exp)


if __name__ == "__main__":
    exp = '-1-4*(3-10*(3*2-1*9/(3-4*5+ 4/2)))  +  10.5 - (4+7)'

    no_space_exp = re.sub(' ', '', exp)
    ret = execute(no_space_exp)
    fnl = compute(ret)
    print('fnl result: ', fnl)

相关文章

  • Python计算器之正则表达式实现

  • 1.正则表达式

    Python通过标准库中的re模块来支持正则表达式。 1. 正则表达式的基本符号 2. python实现正则表达式...

  • python的正则表达式

    python提供了实现正则表达式的re模块。 正则表达式的匹配字符: python的re模块常用函数 1.comp...

  • Python ☞ day 11

    Python学习笔记之 正则表达式 re模块概述:Python自1.5以后增加了re的模块,提供了正则表达式模式...

  • day7-计算器

    通过视频学习,学习了python中怎么实现一个计算器,主要运用了wxPython 库。原视频中是python2.7...

  • 正则表达式

    Python正则表达式初识(一) Python正则表达式初识(二) Python正则表达式初识(三) Python...

  • Python计算器之逆波兰实现

  • 正则表达式

    Python:正则表达式Python:正则表达式

  • 安卓实现简单计算器

    实现一个计算器 ,有加减乘除功能,小数点和清除操作。 这是学校安卓老师布置的作业,计算器说实话实现起来挺多坑的,之...

  • Python正则表达式指南

    Python正则表达式指南 本文介绍了Python对于正则表达式的支持,包括正则表达式基础以及Python正则表达...

网友评论

      本文标题:Python计算器之正则表达式实现

      本文链接:https://www.haomeiwen.com/subject/nkmgzttx.html