File tree Expand file tree Collapse file tree 1 file changed +12
-34
lines changed
Expand file tree Collapse file tree 1 file changed +12
-34
lines changed Original file line number Diff line number Diff line change 1212before attempting to run it on the Bracketeer™.
1313"""
1414
15- LEFT : str = "[{("
16- RIGHT : str = "]})"
1715PAIRS : dict = {
18- "[ " : "] " ,
19- "{ " : "} " ,
20- "( " : ") " ,
16+ "] " : "[ " ,
17+ "} " : "{ " ,
18+ ") " : "( " ,
2119}
2220
2321
@@ -38,40 +36,20 @@ def is_paired(input_string: str) -> bool:
3836 return True
3937
4038 # Remove all non bracket items and convert a string to a list.
41- brackets_list : list = [
39+ brackets_list : list [ str ] = [
4240 bracket for bracket in input_string if bracket in "(){}[]"
4341 ]
4442
4543 # Odd number of brackets
4644 if len (brackets_list ) % 2 != 0 :
4745 return False
4846
49- paired : bool = True
50- while paired and brackets_list :
51- for i , bracket in enumerate ( brackets_list ) :
52- # Right side bracket found
53- if bracket in RIGHT :
54- paired = False
55- break
47+ stack : list [ str ] = []
48+ for bracket in brackets_list :
49+ if bracket in "({[" :
50+ stack . append ( bracket )
51+ elif bracket in PAIRS :
52+ if not stack or stack . pop () != PAIRS [ bracket ]:
53+ return False
5654
57- # No matching pair found
58- if (
59- brackets_list [i + 1 ] != PAIRS [bracket ]
60- and brackets_list [- 1 ] != PAIRS [bracket ]
61- ):
62- paired = False
63- break
64-
65- # Matching pair found next to it
66- if brackets_list [i + 1 ] == PAIRS [bracket ]:
67- del brackets_list [1 ]
68- del brackets_list [0 ]
69- break
70-
71- # Matching pair found at the end of the list
72- if brackets_list [- 1 ] == PAIRS [bracket ]:
73- del brackets_list [0 ]
74- del brackets_list [- 1 ]
75- break
76-
77- return paired
55+ return not stack
You can’t perform that action at this time.
0 commit comments