Curly brackets validation
Ok todays problem was to write some code to make sure that brackets in code where in the right order, so for example
({[]}) - Valid {{()} - Not Valid
So basically each bracket has to be opened and closed properly.
Took me a while but got it working, kept it simple to read I hope, it is a little bit iffy for my liking and I think can be done simpler so will re-visit this one when I have time. Code below have a look.
def validBraces(string):
type1 = '{}'
type2 = '[]'
type3 = '()'
opening_count = 0
closing_count = 0
opening_braces = '{[('
closing_braces = '}])'
opening_string = ''
for character in string:
#evaluate the character
if character in opening_braces:
opening_string += character
opening_count += 1
if character in closing_braces:
closing_count += 1
if character in type1:
if len(opening_string)>0:
if type1[0] == opening_string[-1]:
opening_string = opening_string[:-1]
if character in type2:
if len(opening_string)>0:
if type2[0] == opening_string[-1]:
opening_string = opening_string[:-1]
if character in type3:
if len(opening_string)>0:
if type3[0] == opening_braces[-1]:
opening_string = opening_string[:-1]
if len(opening_string) == 0 and opening_count == closing_count:
return(True)
else:
return(False)