Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import sys
- import math
- def calc(o1, oper, o2):
- if oper == '+': return o1 + o2
- if oper == '-': return o1 - o2
- if oper == '*': return o1 * o2
- if oper == '/': return o1 // o2
- if oper == '^': return int(math.pow(o1, o2))
- def compare_priority(oper1, oper2):
- priority = {'+':0, '-':0, '/':1, '*':1, '^':2}
- return priority[oper1] - priority[oper2]
- def is_oper(e):
- return e in list("+-/*^")
- def is_paren(e):
- return e in ['(', ')']
- def is_unary(e):
- return e in ['-', '+']
- def calc_at_idx(parsed_exp, idx):
- new_val = calc(parsed_exp[idx - 3], parsed_exp[idx - 2], parsed_exp[idx - 1])
- del parsed_exp[idx - 3]
- del parsed_exp[idx - 3]
- #print("got", new_val)
- parsed_exp[idx - 3] = new_val
- expression = sys.argv[1].replace(' ', '')
- parsed_exp = []
- acc = ''
- for c in expression:
- if c in '+-*/^()':
- if acc:
- parsed_exp.append(int(acc))
- acc = ''
- parsed_exp.append(c)
- else:
- acc += c
- if acc: parsed_exp.append(int(acc))
- idx = 0
- openp_idx = -1
- while len(parsed_exp) > 1:
- #print(parsed_exp)
- #print(idx)
- if parsed_exp[idx] == '(':
- openp_idx = idx
- elif parsed_exp[idx] == ')' and idx - openp_idx >= 4:
- # (14 - 5) -> (9)
- calc_at_idx(parsed_exp, idx)
- idx = -1
- elif parsed_exp[idx] == ')' and idx - openp_idx == 2:
- # (5) -> 5
- del parsed_exp[idx]
- del parsed_exp[idx-2]
- idx = -1
- elif (idx == 0 or parsed_exp[idx-1] == '(') and is_unary(parsed_exp[idx]):
- # unary + or -
- # +5 -> 5
- # -(5+2) -> -1 * (5+2)
- if parsed_exp[idx] == '+':
- del parsed_exp[idx]
- idx -= 1
- else:
- parsed_exp[idx] = '*'
- parsed_exp.insert(idx, -1)
- idx = -1
- elif is_oper(parsed_exp[idx]) and is_oper(parsed_exp[idx-2]):
- # 4*5+1 (calc on a lower priority operand)
- if compare_priority(parsed_exp[idx], parsed_exp[idx-2]) <= 0:
- calc_at_idx(parsed_exp, idx)
- idx = -1
- else:
- pass
- elif idx == len(parsed_exp) - 1 and is_oper(parsed_exp[idx-1]):
- # 5-4 (calc on end of expr)
- calc_at_idx(parsed_exp, idx+1)
- idx = -1
- idx += 1
- result = parsed_exp[0]
- print(expression, '=', result)
- if len(sys.argv) == 3:
- if result == int(sys.argv[2]):
- print("PASS")
- else:
- print("FAIL")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement