0

I need to do the following question:

Turn a line of input containing matching pairs of round (()) or curly ({}) brackets into a mountain range. The height of the mountain should indicate how deeply nested the brackets are.

For example, given this input:

{({(){}()}{(){}()})({(){}()}{(){}()})({(){}()}{(){}()})}

Your program should output:

   (){}()  (){}()    (){}()  (){}()    (){}()  (){}()
  {      }{      }  {      }{      }  {      }{      }
 (                )(                )(                )
{                                                      }

If the brackets are not balanced (that is, a matching bracket appears when some of the brackets in the middle have not been closed), the program should print 'Invalid input!'.

please help!

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by slate
0

Pretty printing is left as an exercise.
Edit: Error message on incomplete input.

inp="{({(){}()}{(){}()})({(){}()}{(){}()})({(){}()}{(){}()})}"
levels=list() # list of item, level pairs
stack=list()
cl=0 #current level
other={")":"(","}":"{"}
for it in inp:
  if it in ("(","{"):
    stack.append((it,cl))
    levels.append((it,cl))
    cl+=1
  else:
    if len(stack)==0 or other.get(it,'Impossible input')!=stack[-1][0]:
      print "Invalid input!"
      break
    else:
      m=stack.pop()
      levels.append((it,m[1]))
      cl=m[1]
else:
  if len(stack)!=0:
    print "Invalid input!"
  else:
    print levels
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.