Advertisement
Darryl-Medley

Advanced Polish Notation File Calc

Apr 28th, 2014
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.54 KB | None | 0 0
  1. # Advanced Polish Notation file calculation program
  2. # Written on 04/28/2014 by Darryl Medley for Coding 101 on the TWiT network
  3. # This advanced version calculates expressions of as many terms as memory allows
  4.  
  5. # This program reads a text file called pnequation_list.txt that is in the same folder
  6. # as the .py program file. The file must contain one expression per line and be in
  7. # Polish (aka prefix) notation. Example: +, 12.5, 24.3
  8. # See end of the program for a sample file
  9.  
  10.  
  11. # Polish Notation Calculation function - based on the sample code in Wikipedia
  12. # Parameters:
  13. #   termsList = list containing the expression to evaluate, 1 term per list element
  14. #   pncErrMsg = error message list. Pass in an empty list with the same name
  15. # returns the result if calc is successful, 0 otherwise
  16. def PNCalc(termsList, pncErrMsg):
  17.     oprnd1 = 0.0
  18.     oprnd2 = 0.0
  19.     stk = []   # Stack list
  20.  
  21.     # evaluate in reverse order so we can use a simpler code
  22.     for oper in reversed(termsList):
  23.         if oper in "+-*/%":
  24.             # if an operator is found the stack should have a least 2 operands to calc
  25.             if len(stk) < 2:
  26.                 pncErrMsg.append("Invalid Polish Notation Expression")
  27.                 return 0
  28.  
  29.             try:
  30.                 oprnd1 = float(stk.pop())   # pop operands off of the stack
  31.                 oprnd2 = float(stk.pop())
  32.                 if (oper in "/%") and (oprnd2 == 0.0):
  33.                     pncErrMsg.append("Division by Zero")
  34.                     return 0
  35.                 else:
  36.                     # calculate and put result on the stack
  37.                     stk.append(eval(str(oprnd1)+" "+oper+" "+str(oprnd2)))
  38.             except:
  39.                 pncErrMsg.append("Invalid Polish Notation Expression")
  40.                 return 0
  41.                
  42.         else:   # must be an operand (number)
  43.             stk.append(oper)   # put on the stack
  44.                
  45.     return stk.pop()   # the final result is the only thing left on the stack
  46.  
  47.  
  48. # Begin main program    
  49. print "Advanced Polish (prefix) Notation Equation File Processor"
  50. fname = "./pnequation_list.txt"
  51. try:
  52.     eqlstFile = open(fname, "r")  # open the text file
  53. except:
  54.     print "Error: File",fname,"does not exist"
  55. else:
  56.     # The first thing we do is read the file into a Python list. Each line in
  57.     # the file becomes a string element in the list. .splitlines() removes the
  58.     # \n (newline) character from the end of each line.
  59.     eqList = eqlstFile.read().splitlines()   # read file into list and strip newline characters
  60.     eqlstFile.close()   # We're done with the file now that the lines are in a list
  61.  
  62.     # Process each equation in the list
  63.     for eqLine in eqList:
  64.         if eqLine.strip():   # skip blank lines - True if eqLine is not empty
  65.             # Parse the equation string into operator and operands by creating a little list using split()
  66.             opList = [s.strip() for s in eqLine.split(',')] # strip blanks and parse sting into a list
  67.            
  68.             pncErrMsg = []
  69.             calcResult = PNCalc(opList, pncErrMsg)
  70.  
  71.             if not pncErrMsg:   # pncErrMsg is empty. No errors were found with the equation line
  72.                 print eqLine,"=",calcResult
  73.             else:
  74.                 print eqLine,"= Error:",pncErrMsg[0]
  75.                
  76. print
  77. raw_input("(press Enter to close)")
  78.  
  79. # Sample Test File (save as pnequation_list.txt):
  80. # +, 12.5, 24.3
  81. # x, 1, 2
  82. # -, 23, zz
  83. # +, 1
  84. # *, 7, 19
  85. #
  86. # /, 33.0, 5.0
  87. # /, 33, 0
  88. # %, 5, 3
  89. # -, *, /, 15, -, 7, +, 1, 1, 3, +, 2, +, 1, 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement