Write a calculator in Python

Source: Internet
Author: User

Import reres= ' 1-2 * ((60-30 + (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14) * ( -40/5))-( -4*3)/(16-3*2)) ' Res=res.replace ( ",") Print (eval (res)) # Print (Re.findall (R '-?[ \d\.] +|\+|\-|\*|/', res)) def grep (list): #过滤符号 list=list.replace ("+ +", "+") list=list.replace (' +-', '-') list=list.re Place ('-+ ', '-') list=list.replace ('--', ' + ') return listdef Jisuan (list,x): #计算乘除 index=list.index (x) if x==    ' * ': num=float (List[index-1]) *float (list[index+1]) else:num=float (list[index-1])/float (list[index+1])    Del List[index-1],list[index-1],list[index-1] List.insert (INDEX-1,STR (num)) return listdef jisuan2 (list): #计算加减 Index=list.index (' + ') num = float (list[index-1]) +float (List[index + 1]) del list[index-1], list[index-1], List[index-1] List.insert (index-1, str (num)) return listdef Pangduan (list): #判断计算先后顺序 while 1:if ' * ' in list and '/' is List:jisuan (list, ' * ') elif '/' in List and ' * ' Not In List:jisuan (list, '/') elif ' * ' in the list and '/' in List:a=list.index (' * ') b=list. Index ('/') if A>b:jisuan (list, ' * ') Else:jisuan (list, '/') E Lif ' + ' in list:jisuan2 (list) Else:num = 0 for i in List:num+=flo at (i) Return numdef Zhaokuohao (string): #寻找所有里层括号, and parentheses and evaluates the result Res1=re.search (' \ ([^ ()]+\) ', string) if Res1 : Kuohao=res1.group () Mylist=re.findall (R '-?[ \d\.]        +|\+|\-|\*|/', Res1.group ()) X=pangduan (mylist) string=string.replace (KUOHAO,STR (x)) # Print (x) String=grep (String) # Print (string) return Zhaokuohao (String) Else: # Print (String) retur N Stringdef End (string): #处理剩下无括号的外层 B=re.findall (R '-?[ \d\.] +|\+|\-|\*|/', string) print (Pangduan (b)) End (Zhaokuohao (res)) End (Zhaokuohao (' + + '))

Write a calculator in Python

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.