Python pile

Asked

Viewed 470 times

-3

I am unable to solve an exercise using python stack...

A sequence of parentheses "(" ")", brackets "[" "]" and keys "{" "}" is said to be balanced if each "open" symbol is "closed" at an appropriate time. I need to write a "balanced" function that takes a string and returns "True" if the string represents a balanced sequence, "False" if not.

The function will only receive parentheses, brackets and keys.

I thought so.... but it’s not working out so well... inserir a descrição da imagem aqui

  • Tatiane, try to put the code and not the image of it, please, it is easier for people to analyze and answer you.

1 answer

2

Tatiane, your first if seeing the value of i is incorrect, and its verification in the second if, it is necessary to be isolated with parentheses, see a possible correction:

def balanceada(string):
  pilha = []
  for i in string:
    #Aqui as condições de igualdade estavam erradas
    #if i =='(' or '[' or '{':
    if i =='(' or i =='[' or i == '{':
      pilha.append(i)
    else:
      topo = pilha[-1]
      #Cuidado ao utilizar OR, normalmente temos que isolar com parênteses
      #if i == ")" and topo == "(" or i == "]" and topo == "[" or i == "}" and topo == "{"
      if ( 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

print( balanceada("()[]{}") )
print( balanceada("{[})") )

Browser other questions tagged

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