Search code examples
pythondictionaryreturncompareparentheses

Balanced Parentheses Program Python: Match Function Returning Incorrect Value


so I'm trying to do the "are the string of parentheses balanced?" program in Python and while my balanced function is working properly, the function that I created to check if the parentheses are a match is returning incorrect values. I'm going to attach the whole code, comments and all so that you can see. The first way I tried to do it was with conditional if/else statements. For that approach I kept getting False even if the parentheses were a match. For the second approach I kept getting TypeError: . This is my code.

from collections import deque 

stack = deque()

#dir(stack)

#use a stack to see if an input string has a balanced set of parentheses

#function that tells which parentheses should match. will be used later

def is_match(paren1, paren2):

#dictionary for more efficiency rather than a bunch of conditionals
#match_dict = {
   # ')': '(',
   # ']': '[',
   # '}': '{'
#}

if paren1 == '(' and paren2 == ')':
    return True
if paren1 == '[' and paren2 == ']':
    return True
if paren1 == '{' and paren2 == '}':
    return True 
else:
    return False


#print(match_dict[paren1] == paren2)
#return match_dict[paren1] == paren2

def is_balanced(string):

#start with an iterative for loop to index through the string 
for i in string: 
    
    #check to see if the index of the string is an open parentheses, if so, append to stack
    if i in '([{':
        stack.append([i])
        print(i)
        
    #if index is not in substring, check to see if string is empty 
    else:
        if len(stack) == 0:
            return 'not balanced'
        else:
            match = stack.pop()
            if is_match(match, i) == True:
                return 'balanced'
            else:
                return 'not balanced'
  
    

string = ('([{}])')

is_balanced(string)


Solution

  • Use stack.append(i) instead of stack.append([i]) to add the element i to the deque:

    def is_balanced(string):
        # start with an iterative for loop to index through the string
        for i in string:
    
            # check to see if the index of the string is an open parentheses, if so, append to stack
            if i in "([{":
                stack.append(i)  # <- HERE!
                print(i)
    
            # ...
    

    If you want to extend the deque by appending elements from an iterable argument ([i]), use extend:

    stack.extend([i])
    

    See Python documentation for more information.