fixed issue#171

This commit is contained in:
Danni 2017-10-20 12:35:53 -04:00
parent 535cbb76a3
commit b0d53015fe

View File

@ -18,28 +18,20 @@ returns true if S is nested and false otherwise.
def is_balanced(S): def is_balanced(S):
stack = [] stack = []
open_brackets = set({'(', '[', '{'})
closed_brackets = set({')', ']', '}'})
open_to_closed = dict({'{':'}', '[':']', '(':')'})
for i in range(len(S)): for i in range(len(S)):
if S[i] == '(' or S[i] == '{' or S[i] == '[': if S[i] in open_brackets:
stack.append(S[i]) stack.append(S[i])
else: elif S[i] in closed_brackets:
if len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != S[i]):
if len(stack) > 0:
pair = stack.pop() + S[i]
if pair != '[]' and pair != '()' and pair != '{}':
return False
else:
return False return False
if len(stack) == 0: return len(stack) == 0
return True
return False
def main(): def main():
@ -48,7 +40,7 @@ def main():
if is_balanced(S): if is_balanced(S):
print(S, "is balanced") print(S, "is balanced")
else: else:
print(S, "is not balanced") print(S, "is not balanced")