• 计算器加减乘除(去括号待完善)


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

    import re


    def cheng(suanshi):
    try:
    while 1:
    x = re.search(r'-?d+(.d+)?[*/]d+(.d+)?', suanshi)
    a, b, c = re.split(r'([*/])', x.group())
    a = float(a)
    c = float(c)
    if b == '*':
    res = a * c
    elif b == '/':
    res = float(a / c)
    suanshi = suanshi.replace(x.group(), str(res), 1)
    except Exception:
    obj = re.search('([^()]+)', suanshi)
    print(obj)
    if not obj.group():
    return suanshi[1:-1]
    return suanshi


    def jia(suanshi):
    try:
    while 1:
    x = re.search(r'-?d+(.d+)?[-+]d+(.d+)?', suanshi)
    lst = re.split(r'([-+])', x.group())
    if len(lst) == 5:
    q, w, a, b, c = lst
    if b == '+':
    res = - float(a) + float(c)
    elif b == '-':
    res = -(float(a) + float(c))
    elif len(lst) == 3:
    a, b, c = lst
    if b == '+':
    res = float(a) + float(c)
    elif b == '-':
    res = float(a) - float(c)
    suanshi = suanshi.replace(x.group(), str(res), 1)
    print(suanshi)
    except Exception:
    return suanshi


    # user = input('请输入算式:')
    user = '1-2*((60-30+(-40/5)*(9-2*5/4+7/2+10*14/7))-(-4*3)/(16-3*2))'
    while 1:
    lst = re.findall('([^()]+)', user)
    print(lst)
    if not lst:
    res = jia(cheng(user))[1:-1]
    user = user.replace('--', '+')
    user = user.replace('+-', '-')
    continue
    for i in lst:
    user = user.replace(i, cheng(i), 1)
    print(user)
    lst2 = re.findall('([^()]+)', user)
    for j in lst2:
    user = user.replace(j, jia(j), 1)
    print(user)
  • 相关阅读:
    oracle 的一点累积
    ZT: 网页的一些技巧
    ZT: WEB学习资料
    开源java
    倒序显示文本
    plsql使用之debug
    转 一些shell经验
    lpad rpad
    2018.8.19 2018暑假集训之maxnum
    2018.8.17 题解 2018暑假集训之编辑距离
  • 原文地址:https://www.cnblogs.com/zjx1/p/10828176.html
Copyright © 2020-2023  润新知