[Algo] 스택기반 코드 린터

GisangLee·2022년 8월 29일
0

알고리즘

목록 보기
5/5

1. Stack

후입 선출

데이터는 맨 마지막에만 추가할 수 있고

데이터는 맨 마지막부터 삭제할 수 있다.

  • 설거지를 할 때 접시를 하나씩 올려놓고
    맨 위에 있는 접시부터 닦기 때문에 설거지는 Stack 기반 알고리즘이다.

2. 스택 기반 코드 린터 만들기

class CodeLinter(object):

  def __init__(self, code):

    self.__code = code
    self.__opening_brace = ["(", "[", "{"]
    self.__closing_brace = [")", "]", "}"]
    self.__brace_set = {
      "(": ")",
      "[": "]",
      "{": "}"
    }
    self.__stack = []

  def __is_opening_brace(self, char):
    return char in self.__opening_brace

  def __is_closing_brace(self, char):

    return char in self.__closing_brace

  def __does_not_match(self, char, pop_from_stack):

    return char != self.__brace_set[pop_from_stack]

  def __lint(self):

    for c in self.__code:

      if self.__is_opening_brace(c):
        self.__stack.append(c)

      elif self.__is_closing_brace(c):

        if not self.__stack:
          return f"여는 괄호가 없습니다."
          
        pop_from_stack = self.__stack.pop()
 
        if self.__does_not_match(c, pop_from_stack):
          return f"여는 괄호와 닫는 괄호가 맞지 않습니다."


    if self.__stack:
      return f"닫는 괄호가 부족합니다."

    return f"문법 오류가 없습니다."

  def lint(self):
    
    return self.__lint()


js_code = "const a =  y : [ 1, 2, 3 ]}"
code_linter = CodeLinter(js_code)

result = code_linter.lint()
print(result)
      

profile
포폴 및 이력서 : https://gisanglee.github.io/web-porfolio/

0개의 댓글