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


Simple Expression calculator In Python


#calculator for a.b where . can be +,-,*,/,%
exp=raw_input("Enter expression a.b : ");
l=len(exp);
result=0;
x=int(exp[0]);
y=int(exp[2]);
if exp[1]=='+' :
  result=x+y;
elif exp[1]=='-' :
  result=x-y;
elif exp[1]=='*' :
  result=x*y;
elif exp[1]=='/' :
  result=x/y;
elif exp[1]=='%' :
  result=x%y;  
print "Result : ",result;                  

To Run : python cal.py
INPUT : 1+3
OUTPUT : 4

PASCAL TRIANGLE IN PYTHON


#pascal triangle for n height
from __future__ import print_function
h=int(raw_input("Enter Height of triangle : "));
tri=[1,1,1];
index=1;
for x in range(2,h):
   tri.append(1);
   for y in range(index,index+x-1):
      tri.append(tri[y]+tri[y+1]);
   index=index+x;
   tri.append(1);
print (tri); 
index=0;
for x in range(0,h) :
    for m in range(x,h) :
        print (" ",end="");
    for y in range(index,(index+x)+1) :
        print (tri[y]," ",end="");
    index=index+x+1;
    print ("");       
        

To Run : python pascal.py
The output would be like this :
In ubuntu Terminal :