• Python计算不带括号的字符串


    __author__ = 'Alex'
    # -*- coding:UTF-8 -*-
    import re
    import string
    str = "-10+30-20*11+40*21/5-100+70-2*13+14"
    data_list=[]
    sym_list=[]
    
    data_list = re.findall('d+',str)
    sym_list = re.findall('D+',str)
    
    # print (data_list)
    # print (sym_list)
    
    def add (a1,a2,opr):
        if opr == '+':
            flag = False
            return a1+a2
    def sub (a1,a2,opr):
        if opr == '-':
            flag = False
            return a1-a2
    def mul(a1,a2,opr):
        if opr == '*':
            flag = True
            return a1*a2
    def div(a1,a2,opr):
        if opr == '/':
            flag = True
            return a1/a2
    if sym_list[0] == '-':
        data_list[0] = '-%s'%(data_list[0])
        sym_list.remove(sym_list[0])
    print (data_list)
    print (sym_list)
    while sym_list.count('*') != 0 or sym_list.count('/') != 0:
        for i in range(len(sym_list)):
            if sym_list[i] == '*':
                val = mul(float(data_list[i]),float(data_list[i+1]),'*')
                data_list.remove(data_list[i])
                data_list.remove(data_list[i])
                data_list.insert(i,val)
                sym_list.remove(sym_list[i])
                break
            if sym_list[i] == '/':
                val = div(float(data_list[i]),float(data_list[i+1]),'/')
                data_list.remove(data_list[i])
                data_list.remove(data_list[i])
                data_list.insert(i,val)
                sym_list.remove(sym_list[i])
                break
    print (data_list)
    print (sym_list)
    
    while len(sym_list)>0:
        for i in range(len(sym_list)):
            if sym_list[i] == '+':
                val = add(float(data_list[i]),float(data_list[i+1]),'+')
                data_list.remove(data_list[i])
                data_list.remove(data_list[i])
                data_list.insert(i,val)
                sym_list.remove(sym_list[i])
                break
            if sym_list[i] == '-':
                val = sub(float(data_list[i]),float(data_list[i+1]),'-')
                data_list.remove(data_list[i])
                data_list.remove(data_list[i])
                data_list.insert(i,val)
                sym_list.remove(sym_list[i])
                break
    print (data_list)
    print (sym_list)
  • 相关阅读:
    ##JDBC
    《人月神话》阅读笔记(三)
    《人月神话》阅读笔记(二)
    《人月神话》阅读笔记(一)
    记账小软件开发(网页版)(四)
    记账小软件开发(网页版)(三)
    记账小软件开发(网页版)(二)
    记账小软件开发(网页版)(一)
    课程信息管理系统
    Java课程作业之动手动脑(六)
  • 原文地址:https://www.cnblogs.com/python-study/p/5491361.html
Copyright © 2020-2023  润新知