-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_brackets.py
61 lines (47 loc) · 1.53 KB
/
check_brackets.py
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# python3
import os
from collections import namedtuple
Bracket = namedtuple("Bracket", ["char", "position"])
def are_matching(left, right):
return (left + right) in ["()", "[]", "{}"]
def find_mismatch(text):
opening_brackets_stack = []
for i, bracket in enumerate(text):
if bracket in "([{":
opening_brackets_stack.append(Bracket(bracket, i))
if bracket in ")]}":
if len(opening_brackets_stack) == 0:
return i
opening_bracket = opening_brackets_stack[-1].char
if are_matching(opening_bracket, bracket):
opening_brackets_stack.pop()
else:
return i
if len(opening_brackets_stack) != 0:
return opening_brackets_stack[0].position
return -1
def main():
text = input()
mismatch = find_mismatch(text)
if mismatch == -1:
print("Success")
else:
print(str(mismatch + 1))
# def test_main():
# def get_text(path):
# with open(path) as file:
# return file.readline()
#
# directory = "./tests/"
# for filename in os.listdir(directory):
# if not filename.endswith(".a"):
# text = get_text(f"{directory}/{filename}")
# answer = get_text(f"{directory}/{filename}.a")
# result = find_mismatch(text)
# if answer == "Success\n":
# assert result == -1
# else:
# assert int(answer) == result + 1
# print("TEST PASSED")
if __name__ == "__main__":
main()