Python 计算器练手

初学python,拿计算器练练手

版本python3.9

import re

"""
    计算器demo
"""


def inp(s):
    """ 计算入口,传入一个字符串,如:(((489-8)/9)+9-(985*(76-2)))*89 """

    check(s)  # 校验字符串是否合法
    strRE = r'(?<=\()[^()]*(?=\))'
    # 查找括号内容
    brackets = re.findall(strRE, s)
    # 如果有括号就计算括号内的
    while len(brackets) > 0:
        for ss in brackets:
            s = s.replace('(-)'.replace('-', ss), str(calcNoBrackets(ss)))
        brackets = re.findall(strRE, s)
    return calcNoBrackets(s)  # 没有括号之后,计算并返回最终结果


def calcNoBrackets(s):
    """ 传入一个字符串,不包含括号,如:5-9+8*5+85*76/42-1*-8 """

    reStr = r'\d+([.]\d+)?[*/][-]*\d+([.]\d+)?'
    res = re.search(reStr, s)
    while res is not None:
        sr = s[res.regs[0][0]:res.regs[0][1]]
        s = s.replace(sr, str(calcTwoNum(sr)), 1)
        res = re.search(reStr, s)
    reStr = r'-*\d+([.]\d+)?[+-][-]*\d+([.]\d+)?'
    res = re.search(reStr, s)
    while res is not None:
        sr = s[res.regs[0][0]:res.regs[0][1]]
        s = s.replace(sr, str(calcTwoNum(sr)), 1)
        res = re.search(reStr, s)
    return s


def calcTwoNum(s):
    i = re.search(r'(?<=\d)[*\-/+]', s).regs[0][0]
    a = transToNum(s[:i])
    b = transToNum(s[i+1:])
    operator = s[i]
    if operator == '*':
        return a * b
    if operator == '/':
        return a / b
    if operator == '+':
        return a + b
    if operator == '-':
        return a - b


def transToNum(s):
    """ 字符串转数字 """
    if s.isnumeric():
        return int(s)
    # 处理负数
    elif len(s) > 1 and s[1:].isnumeric() and s[0] == '-':
        return int(s)
    # 处理小数
    else:
        return float(s)


def check(s):
    """
    校验字符串是否可用
    """
    res = re.findall('[-+/*0-9().]', s)
    if len(res) != len(s):
        raise ValueError('unusable str:{}'.format(s))
    res = len(re.findall('[/*+-][/*+]', s))
    res += len(re.findall('[(][/*+]', s))
    res += len(re.findall('[/*+-][)]', s))
    res += len(re.findall('[)][0-9]', s))
    res += len(re.findall('[0-9][(]', s))
    res += len(re.findall('[(][)]', s))
    if res > 0:
        raise ValueError('unusable str:{}'.format(s))
    return True
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bdawn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值