You are on page 1of 2

def evaluate_expression(expr):

# Tách các phần tử của biểu thức

parts = []

# Duyệt qua từng ký tự trong biểu thức và tạo các phần tử

current_part = ''

for char in expr:

if char in {'+', '-', '*', '/'}:

# Khi gặp một phép toán, thêm phần tử hiện tại vào danh sách và bắt đầu phần tử mới

parts.append(current_part.strip())

parts.append(char)

current_part = ''

else:

# Thêm ký tự vào phần tử hiện tại

current_part += char

# Thêm phần tử cuối cùng vào danh sách

parts.append(current_part.strip())

# Khởi tạo giá trị đầu tiên

result = float(parts[0])

# Xử lý các phần tử còn lại

for i in range(1, len(parts), 2):

operator = parts[i]

operand = float(parts[i + 1])

# Thực hiện phép toán tương ứng

if operator == '-':
result -= operand

elif operator == '*':

result *= operand

elif operator == '/':

result /= operand

return result

# Chuỗi biểu thức

input_str = '-1-100'

# Đánh giá và in kết quả

result = evaluate_expression(input_str)

print(f"Input: {input_str}")

print(f"Output: {result:.2f}")

You might also like