Sunday, June 2, 2013

Simple bracket checking program (python3)

Hi, I have posted a simple bracket checking program in java. That program is based on stacks. Some other programming languages facilitates to write such a program in much easier. This post is about write such a program in python 3. Enjoy the simple syntax without object oriented classes and objects.
bracketcheck.py code :

def bracketcheck(inputstring):
    inpt=[]
    for i in range(0,len(inputstring)):
        if(inputstring[i]=='('):
            inpt.append('(')
        elif(inputstring[i]=='['):
            inpt.append('[')
        elif(inputstring[i]=='{'):
            inpt.append('{')

            
        elif(inputstring[i]==')'):
            if(len(inpt)>0):
                if(inpt.pop()=='('):
                    print("")
                else:
                    print("incompatible opening bracket for ')' at position "+str(i+1))
            else:
                print("missing the opening bracket for ')' at position "+str(i+1))

                
        elif(inputstring[i]==']'):
            if(len(inpt)>0):
                if(inpt.pop()=='['):
                    print("")
                else:
                    print("incompatible opening bracket for ']' at position "+str(i+1))
            else:
                print("missing the opening bracket for ']' at position "+str(i+1))

                
        elif(inputstring[i]=='}'):
            if(len(inpt)>0):
                if(inpt.pop()=='{'):
                    print("")
                else:
                    print("incompatible opening bracket for '}' at position "+str(i+1))
            else:
                print("missing the opening bracket for '}' at position "+str(i+1))

    if(len(inpt)>0):
        print("error")


def main():
    inputstr=input()
    bracketcheck(inputstr)

main()


The output :