Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var = 'abcdefghijklmnopqrstuvwxyz'
- operators = '+-*/^'
- def polish(alg):
- '''Converts an algebraic expression into reverse polish notation
- e.x. ((a+b)-(x*y)) --> ab+xy*- '''
- # base case - a single variable is the simplest expression
- if len(alg) == 1 and alg in var:
- return alg
- # recursive case - returns expression 1 + expression 2 + operator
- else:
- # construct a list containing a dict detailing every operator with it's index, priority, and value
- priority = 0
- ops = list()
- for key, char in enumerate(alg):
- if char == '(':
- priority += 1
- if char == ')':
- priority -= 1
- if char in operators:
- ops.append({'index': key, 'priority': priority, 'op': char})
- # select the operation with lowest priority as principle operator
- p_op = sorted(ops, key=lambda op: op['priority'])[0]
- pivot = p_op['index']
- # split the algebraic expression into sub expressions and operator
- return polish(alg[1:pivot]) + polish(alg[pivot+1:-1]) + p_op['op']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement