Tuesday 1 April 2014

Stack Operation In Python


#stack of characters
uchar=raw_input("Enter char OR 'q' to STOP  :");
uinput=[];
while 1 :
   if(uchar=='q') :
      break;
   uinput.append(uchar);   
   uchar=raw_input("Next char : ");
print "input is : ",uinput;
leng=len(uinput);   
stack=[];
for x in range(0,leng) :
   stack.append(uinput[x]);
print "1.push\n2.pop\n3.'q' 2 Quit";
choice=raw_input("Enter choice : ");
pchar='a';
popchar='a';   
while 1:
   if choice=='1' :
       pchar=raw_input("Enter char : ");
       stack.append(pchar);
       leng=len(stack);
       print "stack : ",stack;
   if choice=='2' :
       if leng==0 :
           print "stack is empty !"
           break;
       popchar=stack[leng-1];
       stack.pop(leng-1);
       leng=len(stack);
       print "Poped char : ",popchar;
       print "stack : ",stack;
   if choice=='q' :
       break;
   choice=raw_input("Enter coice : ");    
print "final stack is : ",stack;                         

To Run : python stack.py
Input series put into stack and then perform
stack operation PUSH and POP operation on stack
It would Look like this In ubuntu Terminal


No comments:

Post a Comment