所以我差不多完成了这个程序,但我无法弄清楚如何根据这些规则进行适当的异常处理:
您必须处理以下情况(错误):
操作员太多(+ - / *)
操作数太多(双打)
除以零
对于此作业,您将编写一个程序,该程序将计算用户提供的反向波兰语表达式的结果。
您必须使用链接列表来维护此程序的堆栈(堆栈的数组实现不会获得完全信用)。
您必须处理以下情况(错误): 操作员太多(+ - / *) 操作数太多(双打) 除以零
该程序将采用波兰语表达式,将运算符和操作数分隔为单个空格,并使用新行终止表达式。
程序将继续采用并计算表达式,直到用户在一行上输入零(0)后跟一个新行。
您的示例输出应显示所有错误条件的处理以及使用所有操作符。
示例IO :(注意:输出格式不是关键问题)
Input Output
10 15 + 25
10 15 - -5
2.5 3.5 + 6 (or 6.0)
10 0 / Error: Division by zero
10 20 * / Error: Too many operators
12 20 30 / Error: Too many operands
-10 -30 - 20
100 10 50 25 / * - -2 / -40
这是我到目前为止所得到的:
# !/usr/bin/env python
import sys
import re
class LinkedStack:
#LIFO Stack implementation using a singly linked list for storage.
#-------------------------- nested _Node class --------------------------
class _Node:
#Lightweight, nonpublic class for storing a singly linked node.
__slots__ = '_element', '_next' # streamline memory usage
def __init__(self, element, next): # initialize node’s fields
self._element = element # reference to user’s element
self._next = next # reference to next node
def __init__(self):
#Create an empty stack.
self._head = None # reference to the head node
self._size = 0 # number of stack elements
@property
def __len__(self):
#Return the number of elements in the stack.
return self._size
def is_empty(self):
#Return True if the stack is empty.
return self._size == 0
def push(self, e):
#Add element e to the top of the stack.
self._head = self._Node(e, self._head) # create and link a new node
self._size += 1
def pop(self):
i = self._head._element
self._head = self._head._next
self._size -= 1
return i
ls = LinkedStack()
# Changing the operators to behave like functions via lambda
# Needed for stack push and pop rules down below
# '+' : (lambda x, y: x + y) is same as def '+' (x,y): return x + y
operators = {
'+' : (lambda x, y: x + y),
'-' : (lambda x, y: y - x),
'*' : (lambda x, y: x * y),
'/' : (lambda x, y: y / x)
}
def evaluate(tokens):
# Evaluate RPN expression (given as string of tokens)
for i in tokens:
if i in operators:
ls.push(operators[i](ls.pop(), ls.pop()))
else:
ls.push(float(i))
return ls.pop()
def main():
while True:
print("Input the expression: ", end='')
# Read line by line from stdin + tokenize line + evaluates line
tokens = re.split(" *", sys.stdin.readline().strip())
# Output the stack
print("Stack: ",tokens)
# Output result
if not tokens:
break
print("Result: ",evaluate(tokens),'\n')
# Call main
if __name__=="__main__":
main()
答案 0 :(得分:1)
假设某些输入包含n
个数字和o
个运算符。对于有效输入,似乎o == n-1
。所以也许你可以断言o == n-1
。如果运营商太多,那么可能o > n-1
或太少,o < n-1
。为了检测除零,你可以检查给出除法请求的“右手操作数”,并断言它不是零。