-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path012_valid_braces.py
26 lines (22 loc) · 941 Bytes
/
012_valid_braces.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
# Write a function that takes a string of braces, and determines if the order of the braces is valid. It should
# return true if the string is valid, and false if it's invalid.
#
# This Kata is similar to the Valid Parentheses Kata, but introduces new characters: brackets [], and curly braces {
# }. Thanks to @earned for the idea!
#
# All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.
# What is considered Valid?
#
# A string of braces is considered valid if all braces are matched with the correct brace.
# Examples
def checkbrackets(string):
braces = {"(": ")", "[": "]", "{": "}"}
stack = []
for character in string:
if character in braces.keys():
stack.append(character)
else:
if len(stack) == 0 or braces[stack.pop()] != character:
return False
return len(stack) == 0
print(checkbrackets("()[]{}"))