Skip to content
This repository has been archived by the owner on Nov 30, 2022. It is now read-only.

Balanced brackets code in python. #328

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions Basic-Scripts/balanced_brackets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#import od module
import os

'''
SAMPLE INPUT =
3
{[()]}
{[(])}
{{[[(())]]}}

SAMPLE OUTPUT=
YES
NO
YES


'''
def isBalanced(s):
'''

Args:The string
s: String which is to be checked if it has all balanced brackets or no.

Returns: "YES" if the brackets are balanced in the string else it returns "NO".

'''
table = {')': '(', ']': '[', '}': '{'}
stack = []
for x in s:
if stack and table.get(x) == stack[-1]:
stack.pop()
else:
stack.append(x)
if stack:
return "NO"
else:
return "YES"

#main program
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

t = int(input()) #takes the input ie number of test cases from user

for t_itr in range(t):
s = input() #string taken as input from the user

result = isBalanced(s) #isBalanced(s) function will return "YES" if the brackets are balanced else it will return "NO

fptr.write(result + '\n')

fptr.close()