-
Notifications
You must be signed in to change notification settings - Fork 596
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #423 from Kakarot-2000/master
Fixes #422
- Loading branch information
Showing
2 changed files
with
25 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,30 @@ | ||
# simple program to check if an expression is balanced using stack | ||
stack = [] | ||
def checkBalanced(expr): | ||
for i in expr: | ||
if i == "{" or i == "[" or i == "(": | ||
stack.append(i) | ||
elif i == "}" or i == "]" or i == ")": | ||
temp = stack.pop() | ||
if i == "}" and temp != "{": | ||
if not stack: | ||
return False | ||
elif i == "]" and temp != "[": | ||
top = stack.pop() | ||
if i == "}" and top != "{": | ||
return False | ||
elif i == ")" and temp != "(": | ||
elif i == "]" and top != "[": | ||
return False | ||
elif i == ")" and top != "(": | ||
return False | ||
else: | ||
print("Invalid Expression") | ||
return False | ||
|
||
return True | ||
if not len(stack): | ||
return True | ||
else: | ||
return False | ||
|
||
# main function | ||
expr = input() | ||
result = checkBalanced(expr) | ||
if result: | ||
print("Expression is balanced") | ||
if not checkBalanced(expr): | ||
print("Not Balanced") | ||
else: | ||
print("Expression is not balanced") | ||
print('Balanced') |