Dev102.com programming challenge #13

| | Comments (0)

Dev102.com poses this programming challenge:

Your input is a string which is composed from bracket characters. The allowed characters are:'(', ')', '['. ']', '{', '}', '<' and '>'. Your mission is to determine whether the brackets structure is legal or not.

Example of a legal expression: "([](<{}>))".

Example of an illegal expression: "({<)>}".

Provide the most efficient, elegant and simple solution for that problem.

It's pretty obvious to me that you push opening brackets on the stack and pop off closing brackets, ensuring that the correct closing bracket is encountered. Like this:

def Evaluate(str):
  stack = []
  pushChars, popChars = "<({[", ">)}]"
  for c in str :
    if c in pushChars :
      stack.append(c)
    elif c in popChars :
      if not len(stack) :
        return False
      else :
        stackTop = stack.pop()
        balancingBracket = pushChars[popChars.index(c)]
        if stackTop != balancingBracket :
          return False
    else :
      return False
  return not len(stack)

Leave a comment

About this Entry

This page contains a single entry by Hugh Brown published on July 22, 2008 12:35 PM.

PasswordChart was the previous entry in this blog.

Separated shoulder is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.