Python - stack - - balancing

Asked

Viewed 259 times

0

I can’t find the error in this code: A sequence of parentheses "(" ")", brackets "[" "]" and keys "{" "}" is said to be balanced if each "open" symbol is "closed" at an appropriate time

For example '([])' is a balanced sequence '([)]' is not balanced '([]' is not balanced ')' is not balanced '' is balanced * If you see a letter/number (or anything other than (){}[]<> the function should ignore instead of giving an error. my code:

def balanceada(string):
    pilha = []
    for i in string:
        if i != '(' or i != '[' or i != '{' or i != '<' or i != ')' or i != ']' or i != '}' or i != '>':
            pass
        else:
            if i == '(' or i == '[' or i == '{' or i == "<":
                pilha.append(i)
            else:
                topo = pilha[-1]
                if (i == ")" and topo == "(") or (i == "]" and topo == "[") or (i == "}" and topo == "{") or (i == ">" and topo == "<"):
                    pilha.pop()
                else:
                    return False
    if len(pilha) == 0:
        return True
    else:
        return False

when I run the test: self.assertEqual(balanced('([}[])'),False) Assertionerror: True != False

1 answer

0

You have a problem in the first "if" already - "if i is different from "(" OR other than "[" ..." - ra, I cannot be EQUAL to "(" AND "[" at the same time - so the condition will always be true - and you fall in the case where you do nothing (pass).

The correct question would be "if I am different from ... and different from ... then..." - with and instead of or.

However it is not the best way - since the operator in in Python can check if one substring is part of another in a single comparison, it is possible to write, for that first "if" only:

if i not in "()[]{}<>": 
    pass

Another tip is not to use "Else: " and put another "if" inside - in Python there is the keyword elif which already makes a second comparison case the first ifbe false, and just avoid the ladder that your code will turn.

By matching these comparisons, your logic seems to be ok - it should work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.