所以我几乎完成了这个程序,但我不知道如何根据这些规则进行适当的异常处理:
您必须处理以下情况(错误):
运算符过多 (+ - / *)
操作数过多(双精度数)
被零除
迅速的
对于此作业,您将编写一个程序,该程序将计算用户提供的逆波兰表达式的结果。
您必须使用链表来维护此程序的堆栈(堆栈的数组实现不会获得全部功劳)。
您必须处理以下情况(错误): 运算符过多(+ - / *) 操作数过多(双精度数) 除以零
该程序将接受一个波兰表达式,该表达式将运算符和操作数用一个空格分隔,并以新行结束表达式。
程序将继续获取和评估表达式,直到用户在一行中输入零 (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()