'Determine if brackets are balanced. Not getting expected output
# Stack Data Structure.
I just started leaning Data structures and algorithms. After learning Stack I wrote this algorithm for finding that brackets are balanced or not. Bot I don't know why I'm not getting correct output.
class Stack():
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
def peek(self):
if not self.is_empty():
return self.items[-1]
def get_stack(self):
return self.items
I wrote this is_match function which is going to check that given two values are equal or not.
def is_match(a,b):
if a == b :
return True
else:
return False
Here is the main code started for determining that given barckets are balanced or not.
# DETERMINE IF BRACKETS ARE BALANCED
def is_paren_balanced(paren_string):
s = Stack()
is_balanced = True
index = 0
while index < len(paren_string) and is_balanced:
paren = paren_string[index]
if paren in "([{":
s.push(paren)
else:
if s.is_empty():
is_balanced = False
break
else:
top = s.pop()
if not is_match(top, paren):
is_balanced = False
break
index += 1
if s.is_empty() and is_balanced:
return True
else:
return False
I called out is_paren_balanced function and passed some parameter for testing my code, as I have passed balanced bracket but still it is returning output as False.
result = is_paren_balanced("()")
print(result)
Solution 1:[1]
Your is_match function is wrong, it should match each opening parenthesis to the corresponding closing one.
def is_match(a,b):
if (a == "(" and b == ")") or (a == "[" and b == "]") or (a == "{" and b == "}") :
return True
else:
return False
You can write the if statement in cleaner fashion, but that gives you a basic idea.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhinav Mathur |
