Try the shunting-yard algorithm :
dic={"+": lambda x, y:x+y, "-": lambda x, y:xy, "/": lambda x, y:x/y, "%": lambda x, y:x%y, "*": lambda x, y:x*y} def algo(x, op=None, nums=None): if x != "": op = op if op else [] nums = nums if nums else [] item = x[0] if item in ("+","-","%","/","*"): op.append(item) if item.isdigit(): nums.append(item) if item==")": operator = op.pop() opd1, opd2 = int(nums.pop()), int(nums.pop()) ans = dic[operator](opd1, opd2) nums.append(ans) return algo(x[1:], op, nums) else: if op and nums: operator = op.pop() opd1, opd2 = int(nums.pop()), int(nums.pop()) return dic[operator](opd1, opd2) else: return nums[-1] print algo("((3+2)/(1+4))")
source share