티스토리 뷰

python lecture/algorism

[edu] 올바른 괄호

burningrizen 2019. 1. 17. 15:24

-정규식으로 코드가 간단하지만 성능이 느리다.

import re


def is_bracket(s, p=""):
while s != p:
p = s
s = re.sub(r"[\(][^\(\)]*[\)]", "", s)
return not ("(" in s or ")" in s)


-스택을 이용한 빠른 방법

def is_bracket(s):
sk = []
for c in s:
if c == "(":
sk.append(c)
elif c == ")":
if bool(sk):
sk.pop()
else:
return False
return not bool(sk)


'python lecture > algorism' 카테고리의 다른 글

[edu] 몬테카를로 알고리즘 (monte carlo method) 원주률  (0) 2020.01.30
[edu] 행렬의 곱셈  (0) 2018.12.21
[edu] 퀵 소트  (0) 2018.12.19
[edu] 10진수 > n진수 변환  (0) 2018.12.19
[edu] queue (with node)  (0) 2018.12.11
댓글