Advertisement
Guest User

Untitled

a guest
Dec 21st, 2014
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.13 KB | None | 0 0
  1. var = 'abcdefghijklmnopqrstuvwxyz'
  2. operators = '+-*/^'
  3.  
  4.  
  5. def polish(alg):
  6.     '''Converts an algebraic expression into reverse polish notation
  7.        e.x. ((a+b)-(x*y))  -->  ab+xy*- '''
  8.  
  9.     # base case - a single variable is the simplest expression
  10.     if len(alg) == 1 and alg in var:
  11.         return alg
  12.  
  13.     # recursive case - returns expression 1 + expression 2 + operator
  14.     else:
  15.         # construct a list containing a dict detailing every operator with it's index, priority, and value
  16.         priority = 0
  17.         ops = list()
  18.         for key, char in enumerate(alg):
  19.             if char == '(':
  20.                 priority += 1
  21.  
  22.             if char == ')':
  23.                 priority -= 1
  24.  
  25.             if char in operators:
  26.                 ops.append({'index': key, 'priority': priority, 'op': char})
  27.  
  28.         # select the operation with lowest priority as principle operator
  29.         p_op = sorted(ops, key=lambda op: op['priority'])[0]
  30.         pivot = p_op['index']
  31.  
  32.         # split the algebraic expression into sub expressions and operator
  33.         return polish(alg[1:pivot]) + polish(alg[pivot+1:-1]) + p_op['op']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement