반응형
programmers.co.kr/learn/courses/30/lessons/60058
def solution(p):
def isOrdered(string):
stack = []
for i in range(len(string)):
if string[i] == ")":
if not stack:
return False
stack.pop()
else:
stack.append(string[i])
if not stack:
return True ## p has aleady right order.
else:
return False
def divide(string):
opens = 0
closes = 0
for i in range(len(string)):
if string[i]=='(':
opens +=1
else:
closes +=1
if opens == closes: ## balanced
return i
def rvs(string):
result = ''
for i in range(len(string)):
if string[i] == '(':
result += ')'
else:
result += '('
return result
def transfer(string):
if not string:
return ''
i = divide(string)
left, right = string[:i+1], string[i+1:]
if isOrdered(left):
return left + transfer(right)
else:
return '(' + transfer(right) + ')' + rvs(left[1:-1])
return transfer(p)
리스트컴프리헨션을 이용해 rvs 함수를 간단히 하였다.
if else가 섞인 리스트컴프리헨션의 순서는 [() if (조건) else () for () in ()]이다.
def solution(p):
def isOrdered(string):
stack = []
for i in range(len(string)):
if string[i] == ")":
if not stack:
return False
stack.pop()
else:
stack.append(string[i])
if not stack:
return True ## p has aleady right order.
else:
return False
def divide(string):
n = 0
for i in range(len(string)):
if string[i]=='(':
n +=1
else:
n -=1
if n == 0 : ## balanced
return i
def rvs(string):
return ''.join([')' if string[i]=='(' else '(' for i in range(len(string))])
def transfer(string):
if not string:
return ''
i = divide(string)
left, right = string[:i+1], string[i+1:]
if isOrdered(left):
return left + transfer(right)
else:
return '(' + transfer(right) + ')' + rvs(left[1:-1])
return transfer(p)
댓글