zoukankan      html  css  js  c++  java
  • python模块——re模块(简单的计算器功能实现_eval版)

    #!/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)))
  • 相关阅读:
    bzoj 4260REBXOR
    bzoj 1009GT考试
    cf 621E. Wet Shark and Blocks
    cf 507E. Breaking Good
    cf 766#
    bzoj 3732Network
    bzoj 4300绝世好题
    bzoj 4345[POI2016]Korale
    bzoj 4236JOIOJI
    bzoj 4237稻草人
  • 原文地址:https://www.cnblogs.com/Cong0ks/p/9259863.html
Copyright © 2011-2022 走看看