-
Notifications
You must be signed in to change notification settings - Fork 414
/
Copy pathparanthesis_checker.py
41 lines (37 loc) · 1.23 KB
/
paranthesis_checker.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
"""
Paranthesis checker checks to see if in a given array all paranthesis
are closed, if so the function returns true otherwise false.
i.e. {}, [], (), and ([]) would return true, }, or ([)] would return
false. A stack is implemented to check only when a }, ], or ) are
present in array.
Note that if nothing is entered the function returns true.
"""
def parenthesis_check(parenthesis_array):
stack = []
for parenthesis in parenthesis_array:
if parenthesis == '}':
if len(stack) == 0:
return False
prev_parenthesis = stack.pop()
if prev_parenthesis != '{':
return False
elif parenthesis == ']':
if len(stack) == 0:
return False
prev_parenthesis = stack.pop()
if prev_parenthesis != '[':
return False
elif parenthesis == ')':
if len(stack) == 0:
return False
prev_parenthesis = stack.pop()
if prev_parenthesis != '(':
return False
else: stack.append(parenthesis)
if len(stack) > 0:
return False
else:
return True
str = input("Input: ")
arr = list(str)
print(parenthesis_check(arr))