0% found this document useful (0 votes)
2 views1 page

stack

The document contains a Python function that checks if a string of brackets is balanced. It uses a stack to track opening brackets and their positions, returning the position of any unmatched or mismatched brackets. If all brackets are balanced, it returns 'Success'.

Uploaded by

Sonit Marwah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views1 page

stack

The document contains a Python function that checks if a string of brackets is balanced. It uses a stack to track opening brackets and their positions, returning the position of any unmatched or mismatched brackets. If all brackets are balanced, it returns 'Success'.

Uploaded by

Sonit Marwah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

def is_balanced(input_str):

opening_brackets = "([{"
closing_brackets = ")]}"
stack = []
position_stack = []

for i, char in enumerate(input_str, start=1):


if char in opening_brackets:
stack.append(char)
position_stack.append(i)
elif char in closing_brackets:
if not stack:
return i # Unmatched closing bracket found
top = stack.pop()
position_stack.pop()
if (top == "(" and char != ")") or (top == "[" and char != "]") or (top == "{" and char != "}"):
return i # Mismatched brackets found

if not stack:
return "Success" # The input string is balanced
else:
return position_stack[-1] # Unmatched opening bracket found

# Input string
input_str = input("Enter a string with brackets: ")

result = is_balanced(input_str)

if result == "Success":
print("Success")
else:
print(result)

Enter a string with brackets: abc(def)


Success

Enter a string with brackets: ({[]})


Success

Enter a string with brackets: ({}]


4

Enter a string with brackets: (abc{def)+1}]


9

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy