generate functionFri, 10 Mar 2023

An arithmetic expression is written as a string, for example: "10 + 25 - 12" or "10 + 25 - 12 + 20 - 1 + 3", etc. That is, the number of actions can be different. It is necessary to perform the calculation and display the result on the screen. It is assumed that only addition (+) and subtraction (-) are used here as arithmetic operations, and non-negative integers are used as operands. Note that these operators can be written with or without spaces.

def arithmetic(expr): # replace all spaces expr = expr.replace(" ", "") # split at operators expr_arr = re.split('\+|-', expr) print(expr_arr) # iterate for num, op in zip(expr_arr[1:], expr_arr[:-1]): if op == "-": expr_arr[0] = str(int(expr_arr[0]) - int(num)) else: expr_arr[0] = str(int(expr_arr[0]) + int(num)) return expr_arr[0] arithmetic("10+25-12")

Questions about programming?Chat with your personal AI assistant