#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = "loki"
# Usage: Make a Diy Calculator
# example:
# '1 - 2 * ((60-30 +(-40/5) * (9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
import re
RE_RULE = '\([^()]+\)'
def arithmetical(temp):
result = eval(temp)
return result
def main(arithmetic):
step = 0
while 1:
step += 1
result = re.search(RE_RULE, arithmetic)
if result: # if exist '()'
temp_ = result.group()
calc_res = str(arithmetical(temp_))
arithmetic = re.sub(RE_RULE, calc_res, arithmetic, 1) # replace source values, Note!!! must "1" 不然会出现使用相同的结果多次替换
print(arithmetic, "step: %s" % step)
else: # if not '()'
return arithmetical(arithmetic)
if __name__ == '__main__':
print("result: %s" % (main(user_input)))