Chapter 14: Templates and Exceptions

Example 14.1, Page Number 684

In [1]:
def abs(n):                  #absolute function
    if n<0:
        return -n
    else:
        return n

#variables
int1 = 5
int2 = -6
lon1 = 70000
lon2 = -80000
dub1 = 9.95
dub2 = -10.15

#call instantiate functions
print 'abs(%d)=%d' %(int1,abs(int1))       #abs(int)
print 'abs(%d)=%d' %(int2,abs(int2))       #abs(int)
print 'abs(%d)=%d' %(lon1,abs(lon1))       #abs(long)
print 'abs(%d)=%d' %(lon2,abs(lon2))       #abs(long)
print 'abs(%.2f)=%.2f' %(dub1,abs(dub1))   #abs(double)
print 'abs(%.2f)=%.2f' %(dub2,abs(dub2))   #abs(double)
abs(5)=5
abs(-6)=6
abs(70000)=70000
abs(-80000)=80000
abs(9.95)=9.95
abs(-10.15)=10.15

Example 14.2, Page Number 687

In [2]:
#function returns index number of item, or -1 if not found

def find(array, value, size):
    for j in range(size):
        if array[j] == value:
            return j
    return -1


chrArr = [1, 3, 5, 9, 11, 13]     #array
ch = 5                            #value to find

intArr = [1, 3, 5, 9, 11, 13]
int = 6

lonArr = [1, 3, 5, 9, 11, 13]
lo = 11

dubArr = [1.0, 3.0, 5.0, 9.0, 11.0, 13.0]
db = 4.0

print ' 5 in chrArray: index =',find(chrArr,ch,6)
print ' 6 in intArray: index =',find(intArr,int,6)
print '11 in lonArray: index =',find(lonArr,lo,6)
print ' 4 in dubArray: index =',find(dubArr,db,6)
 5 in chrArray: index = 2
 6 in intArray: index = -1
11 in lonArray: index = 4
 4 in dubArray: index = -1

Example 14.3, Page Number 691

In [3]:
MAX = 100               #size of array

class Stack:
    __st = [None]*MAX          #stack: array of any type
    
    def __init__(self):        #constructor
        self.__top = -1        #number of top of stack
        
    def push(self,var):        #put number on stack
        self.__top += 1
        self.__st[self.__top] = var
        
    def pop(self):             #take number off stack
        x = self.__st[self.__top]
        self.__top -= 1
        return x
    
    
     
s1 = Stack()                   #s1 is object of class Stack

#push 3 floats, pop 3 floats
s1.push(1111.1)
s1.push(2222.2)
s1.push(3333.3)
print '1:',s1.pop()
print '2:',s1.pop()
print '3:',s1.pop()

s2 = Stack()                   #s2 is object of class Stack

#push 3 longs, pop 3 longs
s2.push(123123123)
s2.push(234234234)
s2.push(345345345)
print '1:',s2.pop()
print '2:',s2.pop()
print '3:',s2.pop()
1: 3333.3
2: 2222.2
3: 1111.1
1: 345345345
2: 234234234
3: 123123123

Example 14.4, Page Number 694

In [4]:
MAX = 100               #size of array

class Stack:
    __st = [None]*MAX          #stack: array of any type
    
    def __init__(self):        #constructor
        self.__top = -1        #number of top of stack
        
    def push(self,var):        #put number on stack
        self.__top += 1
        self.__st[self.__top] = var
        
    def pop(self):             #take number off stack
        x = self.__st[self.__top]
        self.__top -= 1
        return x
    
    
    
s1 = Stack()                   #s1 is object of class Stack

#push 3 floats, pop 3 floats
s1.push(1111.1)
s1.push(2222.2)
s1.push(3333.3)
print '1:',s1.pop()
print '2:',s1.pop()
print '3:',s1.pop()

s2 = Stack()                   #s2 is object of class Stack

#push 3 longs, pop 3 longs
s2.push(123123123)
s2.push(234234234)
s2.push(345345345)
print '1:',s2.pop()
print '2:',s2.pop()
print '3:',s2.pop()
1: 3333.3
2: 2222.2
3: 1111.1
1: 345345345
2: 234234234
3: 123123123

Example 14.5, Page Number 696

In [5]:
class link:
    def __init__(self):
        self.data = None                     #contains the data
        self.next = None                     #contains the reference to the next node


class linklist:
    def __init__(self):
        self.first = None

    def additem(self, d):
        newlink = link()                     #create a new node
        newlink.data = d
        newlink.next = self.first            #link the new node to the 'previous' node.
        self.first = newlink                 #set the current node to the new one.

    def display(self):
        current = self.first                 #set current to first link
        
        while current:
            print current.data
            current = current.next



            
ld = linklist()              #ld is the object of class linkedlist

#add three doubles to list ld
ld.additem(151.5)
ld.additem(262.6)
ld.additem(373.7)
ld.display()                  #display entire list ld


lch = linklist()              #lch is the object of class linkedlist

#add three chars to list lch
lch.additem('a')
lch.additem('b')
lch.additem('c')
lch.display()                  #display entire list lch
373.7
262.6
151.5
c
b
a

Example 14.6, Page Number 699

In [6]:
class employee:                    #employee class
    
    def __init__(self):
        self.__name = []*80        #employee name
        self.__number = 0          #employee number
        
def ip(e):
    e._employee__name = raw_input("\n   Enter last name: ")
    e._employee__number = input("   Enter number")
    
def op(e):
    print '\n   Name:',e._employee__name
    print '   number:',e._employee__number
    
    
    
    
class link:
    def __init__(self):
        self.data = None                    #contains the data
        self.next = None                    #contains the reference to the next node


class linklist:
    def __init__(self):
        self.first = None

    def additem(self, d):                   #add data item
        newlink = link()                    #make a new link
        newlink.data = d                    #give it data
        newlink.next = self.first           #it points to next link
        self.first = newlink                #now first points to this

    def display(self):
        current = self.first                #set ptr to first link
        while current:                      #quit on last link
            op(current.data)                #print data
            current = current.next          #move to next link
           
            
            
            
lemp = linklist()              #lemp is object of class linkedlist


while True:
    emptemp = employee()           #temporary employee storage 
    ip(emptemp)                    #get employee data from user
    lemp.additem(emptemp)          #add it to linked list 'lemp'
    
    ans = raw_input("Add another (y/n)? ")
    
    if(ans == 'n'):            #when user is done
        break;
        
lemp.display()                 #display entire linked list
   Enter last name: Mendez
   Enter number1233
Add another (y/n)? y

   Enter last name: Smith
   Enter number2344
Add another (y/n)? y

   Enter last name: Chang
   Enter number3455
Add another (y/n)? n

   Name: Chang
   number: 3455

   Name: Smith
   number: 2344

   Name: Mendez
   number: 1233

Example 14.7, Page Number 707

In [7]:
class Range:          #exception class for stack, Note: empty class body
    pass


class Stack:
    
    def __init__(self):                       #construtor
        self.__st = [0 for j in range(3)]     #array of integers
        self.__top = -1
        
    def push(self,var):
        
        if self.__top>=2:            #if stack is full,
            raise Range()            #throw exception
            
        self.__top += 1
        self.__st[self.__top] = var
        
    def pop(self):
        
        if self.__top<0:             #if stack is empty,
            raise Range()            #throw exception
            
        m = self.__top
        self.__top -= 1
        return self.__st[m]
    
    
    
s1 = Stack()

try:
    s1.push(11)
    s1.push(22)
    s1.push(33)

    print '1:',s1.pop()
    print '2:',s1.pop()
    print '3:',s1.pop()
    print '4:',s1.pop()            #oops: stack empty
    
except Range as i:
    print 'Exception: Stack Full or Empty'
    
print 'Arrive here after catch (or normal exit)'
1: 33
2: 22
3: 11
4: Exception: Stack Full or Empty
Arrive here after catch (or normal exit)

Example 14.8, Page Number 710

In [8]:
class Full:            #exception class
    pass
    
class Empty:           #exception class
    pass

class Stack:
    
    def __init__(self):                       #construtor
        self.__st = [0 for j in range(3)]     #array of integers
        self.__top = -1
        
    def push(self,var):
        
        if self.__top>=2:            #if stack is full,
            raise Full()             #throw full exception
            
        self.__top += 1
        self.__st[self.__top] = var
        
    def pop(self):
        
        if self.__top<0:              #if stack is empty,
            raise Empty()             #throw empty exception 
            
        m = self.__top
        self.__top -= 1
        return self.__st[m]
    
    
    
s1 = Stack()

try:
    s1.push(11)
    s1.push(22)
    s1.push(33)

    print '1:',s1.pop()
    print '2:',s1.pop()
    print '3:',s1.pop()
    print '4:',s1.pop()                #oops: stack is empty
    
except Full as i:
    print 'Exception: Stack Full'
except Empty as i:
    print 'Exception: Stack Empty'
1: 33
2: 22
3: 11
4: Exception: Stack Empty

Example 14.9, Page Number 712

In [9]:
class Inchex:
    pass

class Distance:                      #Distance class
    
    def __init__(self,ft=0,inc=0):   #constructor 
        
        if inc>=12.0:                #if inches too big,
            raise Inchex()           #throw exception
            
        self.__feet = ft
        self.__inches = inc
    
    def getdist(self):               #get length from user
        self.__feet = input('Enter feet:')
        self.__inches = input('Enter inches:')
        
        if self.__inches>=12.0:      #if inches too big,
            raise Inchex()           #throw exception
    
    def showdist(self):              #display distance
        print self.__feet , '\' -' , self.__inches , '\"'
    
    
    
try:                                #define and initialize dist1
    dist1 = Distance(17,3.5)
    dist2 = Distance()
    dist2.getdist()                 #get dist2 from user

                                    #display all lengths
    print 'dist1 = ',;dist1.showdist()
    print 'dist2 = ',;dist2.showdist()
    
except Inchex as i:                  #catch exception
    print 'Initialization error: inches value is too large.'
Enter feet:5
Enter inches:13.5
Initialization error: inches value is too large.

Example 14.10, Page Number 714

In [10]:
class Inchex:                        #exception class
    
    def __init__(self,ori,inc):      #2-arg constructor
        self.origin = ori            #for name of routine
        self.ivalue = inc            #for faulty inches value

        
class Distance:                      #Distance class
    
    def __init__(self,ft=0,inc=0):   #constructor 
        
        if inc>=12.0:
            raise Inchex("2-arg constructor",inc)
            
        self.__feet = ft
        self.__inches = inc
    
    
    def getdist(self):               #get length from user
        self.__feet = input('Enter feet:')
        self.__inches = input('Enter inches:')
        
        if self.__inches>=12.0:
            raise Inchex("getdist() function",self.__inches)
    
    def showdist(self):              #display distance
        print self.__feet , '\' -' , self.__inches , '\"'
    
    
    
try:                                #define and initialize dist1
    dist1 = Distance(17,3.5)
    dist2 = Distance()
    dist2.getdist()                 #get dist2 from user

    #display all lengths
    print 'dist1 = ',;dist1.showdist()
    print 'dist2 = ',;dist2.showdist()
    
except Inchex as ix:                #exception handler
    print 'Initialization error in',ix.origin,'.\n   inches value of',ix.ivalue,'is too large.'
Enter feet:7
Enter inches:13.5
Initialization error in getdist() function .
   inches value of 13.5 is too large.

Example 14.11, Page Number 718

In [11]:
try:
    ptr = []*10000           #allocate memory
    
except MemoryError:          #exception handler
    print "Memory Error Exception: can't allocate memory."
    
del ptr                      #deallocate memory
print "Memory use is successfull."
Memory use is successfull.
In [ ]: