PYTHON   97

postfix

Guest on 30th April 2022 11:57:46 PM

  1.  
  2. def postfix(t) :
  3.     """pre:  t  is a TREE,
  4.          where TREE ::= NUM | [ OP, TREE1, TREE2 ]
  5.       post: ans  is a string holding a postfix (operator-last)
  6.             sequence of the symbols within  t
  7.    """
  8.     print "Translate:", t
  9.     if isinstance(t, str) :  # is  t  a NUM (a string of digits) ?
  10.         ans = t              # the postfix is just the NUM itself
  11.     else :  # t is [op, t1, t2], that is,  isinstance(t, list)
  12.         op = t[0]
  13.         t1 = t[1]
  14.         t2 = t[2]
  15.         ans1 = postfix(t1)
  16.         # assert:  ans1  is the postfix form of t1
  17.         ans2 = postfix(t2)
  18.         # assert:  ans2  is the postfix form of t2
  19.         ans = ans1 + ans2 + op  # append together the strings
  20.     # assert: ans holds the postfix form of  t
  21.     print "The translation of", t, "is", ans
  22.     return ans
  23.  
  24.  
  25.  
  26.  
  27. def postfixx(level, t) :
  28.     """pre:  t  is a TREE,  where TREE ::= INT | [ OP, TREE1, TREE2 ]
  29.             level is an int, indicating at what depth  t  is situated
  30.               in the overall tree being postfixxed
  31.       post: ans  is a string holding a postfix (operator-last) sequence
  32.             of the symbols within  t
  33.    """
  34.     print level * "   ", "Entering subtree t=", t
  35.  
  36.     if isinstance(t, str) :  # is  t a numeral (a simple string)?
  37.         ans = str(t)
  38.     else :  # t is a list, [op, t1, t2]
  39.         op = t[0]
  40.         t1 = t[1]
  41.         t2 = t[2]
  42.         ans1 = postfixx(level + 1, t1)
  43.         ans2 = postfixx(level + 1, t2)
  44.         ans = ans1 + ans2 + op  # combines the two subanswers
  45.  
  46.     print level * "   ", "Exiting subtree t=", t,  "  ans=", ans
  47.     print
  48.     return ans

Raw Paste


Login or Register to edit or fork this paste. It's free.