Python Learning Regular expression exercise: writing a calculator

Source: Internet
Author: User

#!/usr/bin/evn python
ImportRe
defDeal_negative_issue (calc_list):
New_calc_list=[]#定义一个新的空列表, after filtering is complete, put the data into the new list
    forIndex,iteminchEnumerate(calc_list):
offItem.strip (). EndsWith ("*")orItem.strip (). EndsWith ("/"):#挑选出以乘号或除号结尾的字符串
           New_calc_list.append ("%s-%s"% (calc_list[index],calc_list[index+1]))#拼接字符串 Handling similar 2*5/-3
# elif ("*" or "/") in item: #找出列表中的有乘除的选项, I tried it like a match * in, alone 40/5 this match does not come out
        elif("/")inchItemor("*")inchItem
Print(item)
New_calc_list.append (item)

Print("New_calc_ist", new_calc_list)
returnNew_calc_list

defDeal_unusual_issue (Formula):
Formula = Formula.replace ("++","+")
Formula = Formula.replace ("+-","-")
Formula = Formula.replace ("-+","-")
Formula = Formula.replace ("--","+")
Formula = Formula.replace ("- -","+")
returnFormula

# def addition_and_subtraction (Formula):
# sub_calc_list = Re.split ("[+-]", formula)
# sub_operator_list = Re.findall ("[+-]", formula)
# Print (Type (sub_calc_list), sub_operator_list)
# totle_res = None
# for Index,i in Enumerate (sub_calc_list):
# if Totle_res: #sub_res为真, indicating that this is not the first cycle
# if sub_operator_list[index-1]== "+": #通过sub_operator_list中的index判断到底是加法还是减法
# Totle_res + = float (i)
# Else:
# Totle_res-= float (i)
# Else:
# sub_res = float (i)
# Print (totle_res)


defCalculating (Formula):
Print("Operations", formula)
Calc_list = Re.split ("[+-]", formula)#通过 +-symbol separates individual multiplication operations
   Calc_list = Deal_negative_issue (calc_list)
Print(calc_list)
forIteminchCalc_list:
Sub_calc_list = Re.split ("[*/]", item)
Sub_operator_list = Re.findall ("[*/]", item)#将乘号除号通过列表方式分隔出来
        Print(sub_calc_list,sub_operator_list)
Sub_res =None
forIndex,iinchEnumerate(sub_calc_list):
ifSub_res:#sub_res为真, which means it's not the first cycle.
                ifsub_operator_list[index-1]=="*":#通过sub_operator_list中的index判断到底是加法还是减法,
                   Sub_res *=float(i)
Else:
Sub_res/=float(i)
Else:
Sub_res =float(i)

Print("[%s]=]%item,sub_res)
Formula = Formula.replace (item,Str(Sub_res))
Formula = Deal_unusual_issue (Formula)
Print(Formula)

#计算 +-method
   Totle_calc_list = Re.split ("[+-]", formula)
Totle_operator_list = Re.findall ("[+-]", formula)# Multiplication Sign Division sign separated by a list
    Print(Totle_calc_list, Totle_operator_list)
Totle_res =None
forIndex,iteminchEnumerate(totle_calc_list):
ifTotle_res:#sub_res为真, which means it's not the first cycle.
            iftotle_operator_list[index-1]=="+":#通过sub_operator_list中的index判断到底是加法还是减法,
               Totle_res + =float(item)
Else:
Totle_res-=float(item)
Else:
Totle_res =float(item)
# return Formula
    Print("[Result]=], Totle_res)
returnTotle_res

defCalc (Formula):
Parentheses_flag =True
    Calc_res=None
whileParentheses_flag:
m = Re.search ("\([^()]*\)", formula)#找出最底层的括号, one for a
        Print(m)
ifM:
# Print (Type (M.group ()))
           Subformula = M.group (). Strip ("()")#把找出来的括号剥离
           Subres = Calculating (Subformula)
Formula = Formula.replace (M.group (),Str(Subres))
Else:
Print("no brackets.")
Print("The end result is", calculating (Formula))
Parentheses_flag =False

if__name__ = =' __main__ ':
res = Calc ("1-2 * ((60-30 + (9-2*5/-3 + 7/3*99/4*2998 +10 * 568/14) * (40/5))-(4*3)/(16-3*2))")
#res = Calc ("2 * (40/5)")



#备注: -40/5 function not implemented



This article is from the "Open World" blog, so be sure to keep this source http://voidyao000.blog.51cto.com/12458042/1908712

Python Learning Regular expression exercise: writing a calculator

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.