[英]Reverse Polish Calculator Exception Handling in Python
因此,我幾乎完成了該程序,但是我無法根據這些規則找出如何進行適當的異常處理:
您必須處理以下情況(錯誤):
運算符過多(+-/ *)
操作數太多(雙精度)
被零除
對於此分配,您將編寫一個程序,該程序將計算用戶提供的Reverse Polish表達式的結果。
您必須使用鏈接列表來維護該程序的堆棧(堆棧的數組實現將不會獲得全部功勞)。
您必須處理以下情況(錯誤):運算符太多(+-/ *)操作數太多(雙精度)除以零
該程序將使用波蘭語表達式,該表達式將運算符和操作數分隔為一個空格,並以換行符終止該表達式。
程序將繼續接受和評估表達式,直到用戶自己在一行中輸入零(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()
假設某些輸入有n
數字且運算符為o
。 對於有效輸入,似乎o == n-1
。 因此,也許您可以斷言o == n-1
。 如果運算符太多,則可能o > n-1
或太少, o < n-1
。 要檢測被零除,您可以檢查給定除法請求的“右操作數”,並斷言它不為零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.