Skip to content

Recursive expression evaluator

1. Problem

괄호와 사칙연산으로 구성된 수학 표현식을 재귀적으로 계산하는 프로그램을 작성하시오.

표현식은 정수, 덧셈(+), 뺄셈(-), 곱셈(*), 나눗셈(/), 괄호((, ))로 구성된다.

연산은 다음 규칙을 따른다.

  1. 괄호 안의 표현식을 먼저 계산한다.
  2. 곱셈과 나눗셈은 덧셈과 뺄셈보다 먼저 계산한다.
  3. 같은 우선순위의 연산은 왼쪽에서 오른쪽으로 계산한다.
  4. 나눗셈 결과는 정수 나눗셈이 아닌 실수로 계산한다.

재귀 함수를 사용하여 괄호 안의 표현식을 처리하고, 전체 수학 표현식의 결과를 계산하시오.

입력된 표현식에는 공백이 포함되지 않는다.

입력

한 줄에 하나의 수학 표현식이 주어진다.

출력

계산 결과를 소수점 둘째 자리까지 출력한다.

제한사항

  • 표현식의 길이는 1 이상 100 이하이다.
  • 정수는 0 이상 100 이하이다.
  • 나눗셈의 분모는 0이 아니다.
  • 괄호는 올바르게 짝지어져 있다.
  • 연산 결과의 절댓값은 1,000,000 이하이다.
  • eval() 함수는 사용할 수 없다.

2. Input example

Example 1

2+(3*4)

Example 2

(8+4)*(6-2)/3

3. Output example

3.1. Example 1

14.00

3.2. Example 2

16.00

4. Explanation

4.1. Example 1

입력된 표현식은 2+(3*4)이다.

괄호 안의 곱셈을 먼저 계산한다.

  • 3 × 4 = 12
  • 2 + 12 = 14

따라서 최종 결과는 14.00이다.

4.2. Example 2

입력된 표현식은 (8+4)*(6-2)/3이다.

괄호 안의 연산을 먼저 계산한다.

  • 8 + 4 = 12
  • 6 - 2 = 4
  • 12 × 4 = 48
  • 48 ÷ 3 = 16

따라서 최종 결과는 16.00이다.

5. Answer

expression = input().strip()
position = 0


def parse_expression():
    global position

    value = parse_term()

    while position < len(expression):
        operator = expression[position]

        if operator not in "+-":
            break

        position += 1
        next_value = parse_term()

        if operator == "+":
            value += next_value
        else:
            value -= next_value

    return value


def parse_term():
    global position

    value = parse_factor()

    while position < len(expression):
        operator = expression[position]

        if operator not in "*/":
            break

        position += 1
        next_value = parse_factor()

        if operator == "*":
            value *= next_value
        else:
            value /= next_value

    return value


def parse_factor():
    global position

    if expression[position] == "(":
        position += 1
        value = parse_expression()
        position += 1
        return value

    number = 0

    while position < len(expression) and expression[position].isdigit():
        number = number * 10 + int(expression[position])
        position += 1

    return number


result = parse_expression()

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