【Python】简单计算器实现(二) |
您所在的位置:网站首页 › 函数计算器按键说明 › 【Python】简单计算器实现(二) |
解决思路:接下来,我们需要对分割出来的数字和运算符进行压栈。而在此之前,我们需要一个函数来判断运算符的优先级顺序。到时候,再根据该函数的判断结果来决定是压栈还是弹栈。 定义函数:def decision(tail_op, now_op) tail_op: 运算符栈的最后一个运算符param now_op: 从算式列表取出的当前运算符return: 1 表示弹栈并运算, 0 表示弹栈, -1 表示入栈步骤一:定义四种运算符优先级。 # 优先级由低到高 rate1 = ['+', '-'] rate2 = ['*', '/'] rate3 = ['('] rate4 = [')']步骤二:将当前运算符与运算符栈中的最后一个运算符,即上一个运算符,进行比较。 情况一:对于栈顶不是括号 “(”,若当前运算符(除了 “)”)优先级更高,则到时候进行压栈;若当前运算符优先级等于或小于上一个运算符优先级,则到时候进行弹栈并运算。 if tail_op in rate1: if now_op in rate2 or now_op in rate3: return -1 else: return 1 elif tail_op in rate2: if now_op in rate3: return -1 else: return 1情况二:对于栈顶是括号 “(”,若 “(” 遇上的是 “)”,则需要弹出 “(”,且丢掉 “)”;若 “(” 遇上的是其它运算符,则都进行压栈。“(” 能遇上 “)” 就说明中间的运算符都已经被处理完毕了,又因为括号没有实际运算含义,所以直接丢弃即可。 elif tail_op in rate3: if now_op in rate4: return 0 # (遇上)时,需要弹出(,且丢掉) else: return -1 # 栈顶元素为(时,只要当前元素不是)都应入栈情况三:对于栈顶是括号 “)”,则对当前运算符都进行压栈。 else: return -1整段代码 def decision(tail_op, now_op): rate1 = ['+', '-'] rate2 = ['*', '/'] rate3 = ['('] rate4 = [')'] if tail_op in rate1: if now_op in rate2 or now_op in rate3: return -1 else: return 1 elif tail_op in rate2: if now_op in rate3: return -1 else: return 1 elif tail_op in rate3: if now_op in rate4: return 0 else: return -1 else: return -1 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |