Write a calculator method using python regular expressions
#!/usr/bin/evn python
import re
def deal_negative_issue(calc_list):
new_calc_list =[] #Define a new empty list, and then put the data into the new list after filtering is completed
for index,item in enumerate(calc_list):
if item.strip().endswith("*") or item.strip().endswith("/"): #Select the string ending with a multiplication sign or division sign
NEW_CALC_LIST.APEND ("%S-%S"%(CALC_LIST [Index], CALC_LIST [Index+1])) "*" or "/") in item: #Find the options with multiplication and division in the list. I tried this way of writing and it seems that it only matches *, but 40/5 alone cannot match
elif ("/ ") in item or ("*") in item:
print(item) new_calc_list.append(item)
print("new_calc_ist",new_calc_list)
return new_calc_list
def deal_unusual_issue(formula):
formula = formula.replace("++","+")
formula = formula.replace(" +-", "-")
formula = formula.replace("-+", "-")
formula = formula.replace("--", "+")
formula = formula .replace("- -", "+")
return formula
# 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 ):
# ‐ ’ s ’ s ’s ’ s ’ s ’ s ’ s ’ s to t 1-- t t t t t t t to t o t t h e s t o f totle_res: #sub_res is true, indicating that this is not the first time
Loop# Determine whether it is plus or subtraction
# Totle_res+=
Float (i)
Else : TOTLE_RES-= Float (i)
## else:
# sub_res use with using out out out out through out off ‐ ‐ ‐ ‐ ‐ ‐ , use using using using through out out through out out through out through through off ‐ ‐ ‐ ‐ ‐ ‐ and ‐ to to calc_list = re.split("[+-]",formula) #Separate each multiplication and division operation by +- sign
calc_list = deal_negative_issue(calc_list)
print(calc_list)
for item in calc_list:
sub_calc_list = re.split("[*/]",item)
sub_operator_list = re.findall("[*/]",item) #Separate the multiplication and division signs in a list
print (sub_calc_list,sub_operator_list)
sub_res = None
for index,i in enumerate(sub_calc_list):### if sub_res: #sub_res is true, indicating that this is not the first cycle###if sub_operator_list[index-1]=="*": #Determine whether it is addition or subtraction based on the index in sub_operator_list,
sub_res /= float(i )
out ’ way way way ‐ ‐ ‐ ‐ and ‐ ‐ ‐ ‐ to ‐ ‐ ‐ ‐ res ‐ ‐ res ‐ ‐ ‐ res ‐ ‐ res ‐ ‐ res ‐ ‐ res ‐ ‐ ‐ )
formula = deal_unusual_issue(formula)
print(formula)
totle_calc_list = re.split("[+-]", formula)
totle_operator_list = re.findall("[+-]", formula) # Separate the multiplication and division signs in a list
print(totle_calc_list, totle_operator_list)
totle_res = None
for index, item in enumerate( totle_calc_list):
if totle_res: #sub_res is true, indicating that this is not the first cycle
if totle_operator_list[index-1]=="+": #Determine whether it is addition or subtraction through the index in sub_operator_list.
totle_res += float(item)
totle_res -= float(item)
else:
totle_res=float (item)
# return formula
print( "[result]=", totle_res)
return totle_res
def calc(formula):
parentheses_flag = True
calc_res = None
while
parentheses_flag:
m = re.search("\([^()]*\)",formula) #Find the bottom brackets, one by one
print(m)
if m:
#Print (type (m.group ()))
Subformula = m.group (). Strip ("()")#Dip out the found brackets
Subres = Calculating (Subformula) formula = formula.replace(m.group(),str(subres)) else:
print("No brackets")
print("The final 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)")
#Note: -40/5 function is not implemented
The above is the detailed content of Write a calculator method using python regular expressions. For more information, please follow other related articles on the PHP Chinese website!

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

TomakeaPythonscriptexecutableonbothUnixandWindows:1)Addashebangline(#!/usr/bin/envpython3)andusechmod xtomakeitexecutableonUnix.2)OnWindows,ensurePythonisinstalledandassociatedwith.pyfiles,oruseabatchfile(run.bat)torunthescript.

When encountering a "commandnotfound" error, the following points should be checked: 1. Confirm that the script exists and the path is correct; 2. Check file permissions and use chmod to add execution permissions if necessary; 3. Make sure the script interpreter is installed and in PATH; 4. Verify that the shebang line at the beginning of the script is correct. Doing so can effectively solve the script operation problem and ensure the coding process is smooth.

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
