How to check if the parentheses and brackets are balanced? - python

I need to write a function that given a string with parenthesis and/or square brackets it is able to evaluate if they appear in the correct order. For example, in this string '([b])(aa)' you can see that every time a parenthesis or square bracket is open, it is closed in the correct position. However, a string like '[(a])' it is not closing the parenthesis or square brackets in the correct order as it should be '[(a)]'.
The function should return True or False depending on this correct position of both elements. I have tried the following code, but this logic seems to be infinite and it is not working if I have more than two parenthesis or square brackets opened.
def parenthesis(string):
for a in range(len(string)):
if string[a] == "(":
for b in range(a,len(string)):
if string[b] == "[":
for c in range(b,len(string)):
if string[c] == "]":
for d in range(c,len(string)):
if string[d] == ")":
return True
elif string[b] == ")":
return True
else:
return False
If I run the function over the string "([b])(aa)" it is returning false as output.
parenthesis("([b])(aa)")
How can I rewrite this function so it evaluates all the parenthesis and square brackets combinations properly?

If a right parenthesis is open before a left, you got -1 and return False
def is_balanced(string):
cnt = 0
for char in string:
if char == '(': cnt += 1
if char == ')': cnt -= 1
if cnt < 0: return False
return True if cnt == 0 else False

This is one of the stack implementations I know:
def is_balanced(s):
stack = []
for char in s:
if char == "(" or char == "{" or char == "[":
stack.append(char)
elif len(stack) <= 0:
return False
elif char == ")" and stack.pop() != "(":
return False
elif char == "]" and stack.pop() != "[":
return False
elif char == "}" and stack.pop() != "{":
return False
if len(stack) == 0:
return True
return False

This version is more DRY than the prior answer:
def is_balanced(parens: str) -> bool:
# Link: https://stackoverflow.com/a/73341167/
parens_map ={'(':')','{':'}','[':']'}
stack = []
for paren in parens:
if paren in parens_map: # is open
stack.append(paren)
elif paren in parens_map.values(): # is close
if (not stack) or (paren != parens_map[stack.pop()]):
return False
return not stack

Related

Balanced expression with replacement

Given a string that contains only the following => ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate bracket, is it possible to make a valid bracket sequence.
Examples:
Input : S = "{(X[X])}"
Output : Balanced
Input : S = "[{X}(X)]"
Output : Not balanced
I tried to work it out like this, and it works for examples above. But it doesn't work for all examples eg. (it should be balanced but it says it's not)
Input: S = "([X}])"
Output: Not balanced
I tried to work it out but i can't find a solution. Please help.
class Stack:
def __init__(self):
self.data = []
def insert(self, x):
self.data.append(x)
def empty(self):
return len(self.data) == 0
def remove(self):
if self.empty():
raise ValueError('Stack is empty.')
self.data.pop()
def top_element(self):
if self.empty():
raise ValueError('Stack is empty.')
return self.data[-1]
def is_matching(a, b):
if a == "(" and b == ")":
return True
elif a == "[" and b == "]":
return True
elif a == "{" and b == "}":
return True
elif a == "X":
return True
return False
def is_balanced(expression,elements=Stack(),ind=0):
if ind == len(expression):
return elements.empty()
pre_brackets = "([{"
post_brackets = ")]}"
char = expression[ind]
if char in pre_brackets:
elements.insert(char)
return is_balanced(expression,elements,ind+1)
elif char in post_brackets:
if elements.empty() :
return False
if not is_matching(elements.top_element(), char):
return False
elements.remove()
return is_balanced(expression,elements,ind+1)
elif char == "X":
temp = Stack()
temp.insert(char)
result = (is_balanced(expression,temp,ind+1))
if result:
return True
if elements.empty():
return False
elements.remove()
return is_balanced(expression,elements,ind+1)
expression = "([X}])"
if expression == "":
print("No brackets in expression!")
elif len(expression) % 2 != 0:
print("Not balanced")
elif is_balanced(expression):
print("Balanced")
else:
print("Not Balanced")
You can do it by recursively testing all possible replacements for an X:
def can_be_balanced(expr):
pairs = "{}[]()"
opening_brackets = pairs[::2]
closing_brackets = pairs[1::2]
closer = {o:c for o, c in zip(opening_brackets, closing_brackets)}
opener = {c:o for o, c in zip(opening_brackets, closing_brackets)}
stack = []
for item in expr:
if item in opening_brackets:
# we append opening brackets to the stack
stack.append(item)
elif item in closing_brackets:
if not stack or stack[-1] != opener[item]:
# the closing bracket doesn't match the top of the stack
return False
else:
# if it does, we remove the matching opening bracket
stack.pop()
elif item == 'X':
# X could be any of the opening brackets,
possible = list(opening_brackets)
if stack and stack[-1] in opening_brackets:
# or the closing bracket matching the top of the stack
possible.append(closer[stack[-1]])
for pos in possible:
# we replace this X, the first one remaining in expr
test_expr = expr.replace('X', pos, 1)
if can_be_balanced(test_expr):
# This is just in order to print the working solution we just found,
# you may remove these two lines
if not 'X' in test_expr:
print(test_expr)
return True
# None of the replacements for X gave a balanced expression
return False
else:
raise ValueError(f'Invalid item {item} in {expr}')
# The expression is balanced if and only if the stack ends up empty
return not stack
Testing on your sample data:
tests = [("[{X}(X)]", False),
("{(X[X])}", True),
("([X}])", True),
]
for test in tests:
print(test[0], ': should be', test[1])
print(can_be_balanced(test[0]))
print('-'*20)
correctly outputs (with the balanced expression in case it can be done):
[{X}(X)] : should be False
False
--------------------
{(X[X])} : should be True
{([[]])}
True
--------------------
([X}]) : should be True
([{}])
True
--------------------
Note that a major problem in your code is that you only test the end of the expression, starting at the position of the X. Beware also of the mutable default argument elements=Stack() that would leave you with the remnants of the previous call to the function instead of a fresh, empty Stack object.

Using a recursive bisection search to check if a character is in a string

My code is here:
def isIn(char, aStr):
mid = len(aStr)//2
if len(aStr)==0:
return False
elif len(aStr)==1:
if char == aStr:
return True
elif aStr[mid] == char:
return True
if mid == 0 and len(aStr) != 1:
return False
else:
if char > aStr[mid]:
return isIn(char,aStr[mid:] )
else:
return isIn(char,aStr[0:mid])
my code works for when the character is present in the string, if the test case is such that if the character that I want to search in the string is not actually present in the string, then the code goes into an infinite loop.
For example in the test case isIn('m','iloruuyz') the code goes into an infinite loop.
On the if len(aStr) == 1: condition, you only return True if the condition is met, but not False if the condition is not, that is where the infinite loop is occuring :)
def isIn(char, aStr):
mid = len(aStr)//2
if len(aStr)==0:
return False
elif len(aStr)==1:
if char == aStr:
return True
else: # Else return false to stop the infinite loop
return False
elif aStr[mid] == char:
return True
if mid == 0 and len(aStr) != 1:
return False
else:
if char > aStr[mid]:
return isIn(char,aStr[mid:] )
else:
return isIn(char,aStr[0:mid])

Stack Balanced Parenthesis is not working

I have a class Stack that looks like this.
I have this function that checks if given string of parenthesis is valid or not.
After debugging and printing current character and character at peak:
This output matches condition at line 40 ans is supposed to pop the element. But does not.
Here is the full code.
class Stack:
def __init__(self):
self.item = []
def push(self, item):
self.item.append(item)
def pop(self):
self.item.pop()
def isEmpty(self):
return self.item == []
def peek(self):
if not self.isEmpty():
return self.item[-1]
else:
return "Stack is Empty."
def getStack(self):
return self.item
s = Stack()
string = "{[{()}][]}"
print(list(string))
def isValid(String):
for char in string:
# print(char)
print("Peak -> " +s.peek())
print("char -> " + char)
if char == "(" or char == "[" or char == "{":
s.push(char)
elif (char == ")" and s.peek == "("):
s.pop()
elif (char == "]" and not s.isEmpty() and s.peek == "["):
s.pop()
elif (char == "}" and not s.isEmpty() and s.peek == "{"):
s.pop()
else:
return False
return s.isEmpty()
print(isValid(string))
Before checking if statement, char -> ) and s.peak returns -> (.
So, it should be popped but instead doesnt run any if statement and returns false.
(P.S if I use or instead of and, it works(at least for couple I've tried). Shouldn't it work for and and not for or )
Am I missing something? help, someone!
You are comparing strings with function object s.peek == "[". You need to call s.peek().
Change your elif conditions to this
elif char == ")" and s.peek() == "(":
s.pop()
elif (char == "]" and not s.isEmpty() and s.peek() == "["):
s.pop()
elif (char == "}" and not s.isEmpty() and s.peek() == "{"):
s.pop()

Turning iteration into recursion

I want to check if the string user entered has a balanced amount of ( and )'s
ex. ()( is not balanced
(()) is balanced
def check(string):
counter=0
string=string.replace(" ","")
if string[0] is "(":
for x in string:
if x is "(":
counter=counter+1
elif x is ")":
counter=counter-1
if counter1 is 0:
print("Balanced")
else:
print("Unbalanced")
else:
print ("Unbalanced")
so this works, but how do I solve this problem with recursion? I am trying to think how I can make a variable decrease each time i call it recursively and once it's 0, stop.s
>>> def check(mystr, barometer=0):
... if not mystr:
... return barometer
... elif mystr[0] == "(":
... return check(mystr[1:], barometer+1)
... elif mystr[0] == ")":
... return check(mystr[1:], barometer-1)
... else:
... return check(mystr[1:], barometer)
...
>>> for s in ["()", "(()", "(())", "()()"]: print(s, check(s))
...
() 0
(() 1
(()) 0
()() 0
0 means you're properly balanced. Anything else means you're not balanced
A direct, equivalent conversion of the algorithm would look like this:
def check(string, counter=0):
if not string:
return "Balanced" if counter == 0 else "Unbalanced"
elif counter < 0:
return "Unbalanced"
elif string[0] == "(":
return check(string[1:], counter+1)
elif string[0] == ")":
return check(string[1:], counter-1)
else:
return check(string[1:], counter)
Use it like this:
check("(())")
=> "Balanced"
check(")(")
=> "Unbalanced"
Notice that the above algorithm takes into account cases where the closing parenthesis appears before the corresponding opening parenthesis, thanks to the elif counter < 0 condition - hence fixing a problem that was present in the original code.

returning 1 instead of true in python

I am trying to return one instead of true in python.
The code i am working on is:
delimiters = ( '()', '[]', '{}', "''", '""' )
esc = '\\'
def is_balanced(s, delimiters=delimiters, esc=esc):
stack = []
opening = tuple(str[0] for str in delimiters)
closing = tuple(str[1] for str in delimiters)
for i, c in enumerate(s):
if len(stack) and stack[-1] == -1:
stack.pop()
elif c in esc:
stack.append(-1)
elif c in opening and (not len(stack) or opening[stack[-1]] != closing[stack[-1]]):
stack.append(opening.index(c))
elif c in closing:
if len(stack) == 0 or closing.index(c) != stack[-1]:
return False
stack.pop()
return len(stack) == 0
num_cases = raw_input()
num_cases = int(num_cases)
for num in range(num_cases):
s = raw_input()
print is_balanced(s)
It basically checks whether the string typed is balanced or not. If balanced, should return 1 and if not 0.
I tried this:
1
Test string
True
It returns true. I would like it to return 1. How do i do it?
Alternatively you could cast your boolean to an int:
>>>myBoolean = True
>>>int(myBoolean)
1
>>>myBoolean = False
>>>int(myBoolean)
0
Huh? You change the code:
Instead of
return False
write
return 0
and instead of
return len(stack) == 0
write
if len(stack) == 0:
return 1
return 0
The latter 3-liner can be rewritten on a single line, but I chose the above for clarity.
return 1 if len(stack) == 0 else 0
This concisely changes the return value of is_balanced, and is equivalent to:
if len(stack) == 0:
return 1
else:
return 0
Of course you could keep is_balanced unchanged and print (in similar notation):
1 if is_balanced(s) else 0
Just use
print +is_balanced(s)
instead.

Categories