def calculate(expression):
operators = []
operands = []
i = 0
while i < len(expression):
token = expression[i]
if token.isdigit():
num = ""
while i < len(expression) and expression[i].isdigit():
num += expression[i]
i += 1
operands.append(int(num))
elif token == '+':
operators.append(token)
i += 1
elif token == '-':
operators.append(token)
i += 1
elif token == '*':
operators.append(token)
i += 1
elif token == '/':
operators.append(token)
i += 1
elif token == '(':
operators.append(token)
i += 1
elif token == ')':
while operators and operators[-1] != '(':
process_operator(operators, operands)
operators.pop() # Remove the '('
i += 1
while operators:
process_operator(operators, operands)
return operands[0]
def process_operator(operators, operands):
operator = operators.pop()
operand2 = operands.pop()
operand1 = operands.pop()
if operator == '+':
operands.append(operand1 + operand2)
elif operator == '-':
operands.append(operand1 - operand2)
elif operator == '*':
operands.append(operand1 * operand2)
elif operator == '/':
operands.append(operand1 / operand2)
user_input = input("수식을 입력하세요: ")
expression = user_input.replace(" ", "")
result = calculate(expression)
print("결과:", result)
phthon 계산기 예제
2023. 10. 25. 21:41