forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path4.py
More file actions
46 lines (44 loc) ยท 1.31 KB
/
4.py
File metadata and controls
46 lines (44 loc) ยท 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# "๊ท ํ์กํ ๊ดํธ ๋ฌธ์์ด"์ ์ธ๋ฑ์ค ๋ฐํ
def balanced_index(p):
count = 0 # ์ผ์ชฝ ๊ดํธ์ ๊ฐ์
for i in range(len(p)):
if p[i] == '(':
count += 1
else:
count -= 1
if count == 0:
return i
# "์ฌ๋ฐ๋ฅธ ๊ดํธ ๋ฌธ์์ด"์ธ์ง ํ๋จ
def check_proper(p):
count = 0 # ์ผ์ชฝ ๊ดํธ์ ๊ฐ์
for i in p:
if i == '(':
count += 1
else:
if count == 0: # ์์ด ๋ง์ง ์๋ ๊ฒฝ์ฐ์ False ๋ฐํ
return False
count -= 1
return True # ์์ด ๋ง๋ ๊ฒฝ์ฐ์ True ๋ฐํ
def solution(p):
answer = ''
if p == '':
return answer
index = balanced_index(p)
u = p[:index + 1]
v = p[index + 1:]
# "์ฌ๋ฐ๋ฅธ ๊ดํธ ๋ฌธ์์ด"์ด๋ฉด, v์ ๋ํด ํจ์๋ฅผ ์ํํ ๊ฒฐ๊ณผ๋ฅผ ๋ถ์ฌ ๋ฐํ
if check_proper(u):
answer = u + solution(v)
# "์ฌ๋ฐ๋ฅธ ๊ดํธ ๋ฌธ์์ด"์ด ์๋๋ผ๋ฉด ์๋์ ๊ณผ์ ์ ์ํ
else:
answer = '('
answer += solution(v)
answer += ')'
u = list(u[1:-1]) # ์ฒซ ๋ฒ์งธ์ ๋ง์ง๋ง ๋ฌธ์๋ฅผ ์ ๊ฑฐ
for i in range(len(u)):
if u[i] == '(':
u[i] = ')'
else:
u[i] = '('
answer += "".join(u)
return answer