-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbalanced_parentheses.py
More file actions
46 lines (42 loc) · 1.2 KB
/
balanced_parentheses.py
File metadata and controls
46 lines (42 loc) · 1.2 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
# Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
# determine if the input string is valid.
# An input string is valid if:
# - Open brackets are closed by the same type of brackets.
# - Open brackets are closed in the correct order.
# - Note that an empty string is also considered valid.
# ((())) -> True
# [()]{} -> True
# ({[)] or (( or ()[} -> False
s = input()
open_brackets = ['(', '{', '[']
b_list = []
for b in s:
if b in open_brackets:
b_list.append(b)
else:
try:
bracket = b_list.pop()
match bracket:
case '(':
if b != ')':
print('False')
break
case '{':
if b != '}':
print('False')
break
case '[':
if b != ']':
print('False')
break
case _:
print("Invalid String")
break
except IndexError:
print('False')
break
else:
if len(b_list) != 0:
print('False')
else:
print('True')