播种器菜鸡1号 2022-12-10 22:50 采纳率: 81.8%
浏览 110
已结题

python 循环,检查输入表达式是否有误

问题遇到的现象和发生背景

python计算表达式程序,加入一个检查输入表达式是否有误的功能和循环运行功能应该怎么写
如:
input expresion:
-2*(3+5)+2^3/4=
-14
continue or not(y,n)?
y
input expression:
2 3 5+6=
Hint:the expression is wrong in format.

遇到的现象和发生背景,请写出第一个错误信息
用代码块功能插入代码,请勿粘贴截图。 不用代码块回答率下降 50%
import re
express = input("input expression:")
def caculator(eq):
    format_list = eq_format(eq)  # 把字符串变成格式化列表形式
    s_eq = simplify(format_list)  # 去括号,得到无括号的一个格式化列表
    ans = calculate(s_eq)  # 计算最终结果
    if len(ans) == 2:  # 判断最终结果为正数还是负数
        ans = -float(ans[1])
    else:
        ans = float(ans[0])
    return ans

def eq_format(eq):
    format_list = re.findall('[\d.]+|\(|\+|-|\*|/|\)', eq)
    return format_list

def simplify(format_list):
    bracket = 0  # 用于存放左括号在格式化列表中的索引
    count = 0
    for i in format_list:
        if i == '(':
            bracket = count
        elif i == ')':
            temp = format_list[bracket + 1: count]
            new_temp = calculate(temp)
            format_list = format_list[:bracket] + new_temp + format_list[count + 1:]
            format_list = change(format_list, bracket)  # 解决去括号后会出现的-- +- 问题
            return simplify(format_list)  # 递归去括号
        count = count + 1
    return format_list

def calculate(s_eq):
    if '*' or '/' in s_eq:
        s_eq = remove_multiplication_division(s_eq)
    if '+' or '-' in s_eq:
        s_eq = remove_plus_minus(s_eq)
    return s_eq

def remove_multiplication_division(eq):
    count = 0
    for i in eq:
        if i == '*':
            if eq[count + 1] != '-':
                eq[count - 1] = float(eq[count - 1]) * float(eq[count + 1])
                del (eq[count])
                del (eq[count])
            elif eq[count + 1] == '-':
                eq[count] = float(eq[count - 1]) * float(eq[count + 2])
                eq[count - 1] = '-'
                del (eq[count + 1])
                del (eq[count + 1])
            eq = change(eq, count - 1)
            return remove_multiplication_division(eq)
        elif i == '/':
            if eq[count + 1] != '-':
                eq[count - 1] = float(eq[count - 1]) / float(eq[count + 1])
                del (eq[count])
                del (eq[count])
            elif eq[count + 1] == '-':
                eq[count] = float(eq[count - 1]) / float(eq[count + 2])
                eq[count - 1] = '-'
                del (eq[count + 1])
                del (eq[count + 1])
            eq = change(eq, count - 1)
            return remove_multiplication_division(eq)
        count = count + 1
    return eq

def remove_plus_minus(eq):
    count = 0
    if eq[0] != '-':
        sum = float(eq[0])
    else:
        sum = 0.0
    for i in eq:
        if i == '-':
            sum = sum - float(eq[count + 1])
        elif i == '+':
            sum = sum + float(eq[count + 1])
        count = count + 1
    if sum >= 0:
        eq = [str(sum)]
    else:
        eq = ['-', str(-sum)]
    return eq

def change(eq, count):
    if eq[count] == '-':
        if eq[count - 1] == '-':
            eq[count - 1] = '+'
            del eq[count]
        elif eq[count - 1] == '+':
            eq[count - 1] = '-'
            del eq[count]
    return eq


result = caculator(express)
print(result)
if __name__ == '__main__':
    flag=True
    while (flag):
        judge = input("continue or not(y,n)?")
        if (judge == "n"):
            print('end')
        elif (judge == "y"):
            express = input("input expression:")

运行结果及详细报错内容
我的解答思路和尝试过的方法,不写自己思路的,回答率下降 60%
我想要达到的结果,如果你需要快速回答,请尝试 “付费悬赏”

希望最后运行界面大概如下,如果表达式格式有误会提示
input expresion:
-2*(3+5)+2^3/4=
-14
continue or not(y,n)?
y
input expression:
2 3 5+6=
Hint:the expression is wrong in format.

  • 写回答

6条回答 默认 最新

  • 生产队的小刘 Python领域新星创作者 2022-12-12 08:50
    关注
    import re
    
    def check_expression(expression):
      # Use a regular expression to search for the presence of a valid
      # mathematical expression in the input string. This could include
      # numbers, parentheses, and the following mathematical operators:
      # +, -, *, /, ^ (for exponentiation)
      pattern = r"^[\d.+-/*^()]+$"
      return re.search(pattern, expression) is not None
    
    def caculator(eq):
      # Your existing caculator code goes here...
    
    while True:
      # Get the input expression from the user
      express = input("input expression:")
    
      # Check if the expression is valid
      if not check_expression(express):
        # If the expression is not valid, print an error message
        print("Hint:the expression is wrong in format.")
        continue
    
      # If the expression is valid, evaluate it using the caculator function
      result = caculator(express)
    
      # Print the result of the calculation
      print(result)
    
      # Ask the user if they want to continue
      cont = input("continue or not(y, n)?")
      if cont.lower() != "y":
        break
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

问题事件

  • 系统已结题 12月22日
  • 已采纳回答 12月14日
  • 赞助了问题酬金15元 12月11日
  • 创建了问题 12月10日

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分