Chapter 15: The Standard Template Library

Example 15.1, Page Number 735

In [1]:
arr = [11,22,33,44,55,66,77,88]

ptr = arr.index(33)         #find first 33

print 'First object with value 33 found at offset',ptr
First object with value 33 found at offset 2

Example 15.2, Page Number 736

In [2]:
arr = [33,22,33,44,33,66,77,88]

n = arr.count(33)           #count number of 33's

print 'There are',n,'33\'s in arr.\n'
There are 3 33's in arr.

Example 15.3, Page Number 737

In [3]:
arr = [45,2,22,-17,0,-30,25,55]           #array of numbers

arr1 = sorted(arr)            #sort the numbers

for j in range(8):            #display sorted numbers
    print arr1[j],'',
-30  -17  0  2  22  25  45  55 

Example 15.4, Page Number 737

In [4]:
def find_sublist(sub, bigger):      #function for find the substring
    
    if not bigger:
        return -1
    if not sub:
        return 0
    
    first, rest = sub[0], sub[1:]
    pos = 0
    
    try:
        while True:
            pos = bigger.index(first, pos) + 1
            if not rest or bigger[pos:pos+len(rest)] == rest:
                return pos-1
    except ValueError:
        return -1
    
    

source = [11,44,33,11,22,33,11,22,44]
pattern = [11,22,33]

ptr =  find_sublist(pattern, source)

if ptr == -1:                     #if past-the-end
    print "No Match Found"
else:
    print 'Match at',ptr
Match at 3

Example 15.5, Page Number 738

In [5]:
src1 = [2,3,4,6,8]
src2 = [1,3,5]

dest = sorted(src1 + src2)        #merge src1 and src2 into dest and sort it

for j in range(8):                #display dist
    print dest[j],
1 2 3 3 4 5 6 8

Example 15.6, Page Number 739

In [6]:
fdata = [19.2 , 87.4 , 33.6 , 55.0 , 11.5 , 42.2]            #array of doubles

fdata1 = sorted(fdata , reverse = True)         #sort the doubles in reverse order

for j in range(6):             #display sorted doubles
    print fdata1[j],
87.4 55.0 42.2 33.6 19.2 11.5

Example 15.7, Page Number 740

In [7]:
names = ["George", "Penny", "Estelle", "Don", "Mike", "Bob"]         #array of strings

names = sorted(names)           #sort the string

for i in range (6):             #display sorted strings
    print names[i]
Bob
Don
Estelle
George
Mike
Penny

Example 15.8, Page Number 741

In [8]:
names = ["George", "Estelle", "Don", "Mike", "Bob"]

ptr = names.index("Don")             #index of an element

print 'Don is element',ptr,'on the list.'
Don is element 2 on the list.

Example 15.9, Page Number 742

In [9]:
def in_to_cm(inc):                   #convert and display as centimeters
    print inc*2.54,
    
inches = [3.5,6.2,1.0,12.75,4.33]    #array of inches value

for x in range(len(inches)):         #output as centimeters
    in_to_cm(inches[x])
8.89 15.748 2.54 32.385 10.9982

Example 15.10, Page Number 743

In [10]:
def in_to_cm(inc):                   #convert and display as centimeters
    return inc*2.54
    
inches = [3.5,6.2,1.0,12.75,4.33]
centi = [0.0 for j in range(5)]

for x in range(len(inches)):         #transform into array centi[]
    centi[x] = in_to_cm(inches[x])
    
for x in range(len(centi)):          #display array centi[]
    print centi[x],
8.89 15.748 2.54 32.385 10.9982

Example 15.11, Page Number 744

In [11]:
x = []

                #put values at end of array
x.append(10)
x.append(11)
x.append(12)
x.append(13)

                #replace with new values
x[0] = 20
x[3] = 23

                #display array contents
for j in range(x.__len__()):
    print x[j],
20 11 12 23

Example 15.12, Page Number 745

In [12]:
#*class vector*#

class vector:                                               
    
    def __init__(self,a):            #construtor
        
        if isinstance(a,int):
            self.__arr = [0.0 for j in range(a)]
            
        elif isinstance(a,vector):
            self.__arr = a.__arr
        
        else:
            self.__arr = a
            
            
    def swap(self,v2):                  #swap contents of two vectors
        return v2.__arr,self.__arr
    
    def empty(self):                    #check vector is empty or not
        if len(self.__arr)==0:
            return True
        else:
            return False
        
    def back(self):                     #return the last element of vector
        a = len(self.__arr)
        return self.__arr[a-1]
        
    def pop_back(self):                 #delete last element vector 
        self.__arr.pop()
        
        
        
        
arr = [1.1,2.2,3.3,4.4]                 #an array of doubles

v1 = vector(arr)                        #initialize vector to array
v2 = vector(4)                          #empty vector of size 4


v1,v2 = v1.swap(v2)                     #swap contents of v1 and v2

v2 = vector(v2)

while not v2.empty():                   #untill vector is empty
    
    print v2.back(),                    #display the last element
    v2.pop_back()                       #remove last element
4.4 3.3 2.2 1.1

Example 15.13, Page Number 746

In [13]:
arr = [100,110,120,130]              #an array of ints
v = arr                              

print 'Before insertion:',
for j in range(len(v)):              #display all elements
    print v[j],
    
v.insert(2,115)                      #insert 115 at element 2

print '\nAfter insertion: ',
for j in range(len(v)):              #display all elements
    print v[j],
    
v.remove(115)                        #erase element 2

print '\nAfter erasure:   ',
for j in range(len(v)):              #display all elements
    print v[j],

print '\n'
Before insertion: 100 110 120 130 
After insertion:  100 110 115 120 130 
After erasure:    100 110 120 130 

Example 15.14, Page Number 747

In [14]:
class list:                              #*list class*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,a):                 #function to add element in array at last
        self.__arr.append(a)
        
    def size(self):                        #return size of array
        self.__arr = sorted(self.__arr)    #sort the array
        return len(self.__arr)
        
    def front(self):                       #gives the first element
        return self.__arr[0]
    
    def pop_front(self):                   #delete first element
        a = self.__arr[0]
        self.__arr.remove(a)
        
        
        
        
ilist = list()

ilist.push_back(30)              #push items on back
ilist.push_back(40)
ilist.push_back(20)
ilist.push_back(10)

size = ilist.size()              #number of items

for j in range(size):
    print ilist.front(),         #read items from front
    ilist.pop_front()            #pop items off front
10 20 30 40

Example 15.15, Page Number 748

In [15]:
class list:                              #*list class*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,a):                 #function to add element in array at last
        self.__arr.append(a)
        
    def reverse(self):                     #reverse the array
        self.__arr.reverse()
        
    def merge(self,a):                     #merge 'a' perameter to array
        self.__arr.extend(a.__arr)
        
    def unique(self):                      #remove duplicate items from the array
        a = []
        for x in self.__arr:
            if x not in a:
                a.append(x)
        self.__arr = a
        
    def size(self):                        #return size of array
        self.__arr = sorted(self.__arr)    #sort the array
        return len(self.__arr)
    
    def empty(self):                       #check array is empty or not
        if len(self.__arr)==0:
            return 1
        else:
            return 0
        
    def front(self):                       #gives the first element
        return self.__arr[0]
    
    def pop_front(self):                   #delete first element
        a = self.__arr[0]
        self.__arr.remove(a)
        
        
        
        
arr1 = [40,30,20,10]
arr2 = [15,20,25,30,35]

list1 = list()
list2 = list()

for j in range(4):
    list1.push_back(arr1[j])               #list1: 40, 30, 20, 10

for j in range(5):
    list2.push_back(arr2[j])               #list2: 15, 20, 25, 30, 35
    
list1.reverse()                            #reverse list1: 10 20 30 40

list1.merge(list2)                         #merge list2 into list1

list1.unique()                             #remove duplicate 20 and 30

size = list1.size()

while (list1.empty()==False):
    print list1.front(),                   #read item from front
    list1.pop_front()                      #poopitem off front
10 15 20 25 30 35 40

Example 15.16, Page Number 750

In [16]:
class deque:                              #*deque class*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,a):                 #function to add element in array at last
        self.__arr.append(a)
        
    def op1(self,a,b):                     #function to change the item of array
        self.__arr[a] = b
        
    def size(self):                        #reurn size of array
        self.__arr = sorted(self.__arr)    #sort the array
        return len(self.__arr)
    
    def op2(self,n):                       #function to return array item
        return self.__arr[n]
    
        
    
    
deq = deque()

deq.push_back(30)               #push item on back
deq.push_back(40)
deq.push_back(50)
deq.push_back(20)
deq.push_back(10)

k = deq.size()

deq.op1(2,33)                   #change middle item

for j in range(k):
    print deq.op2(j),           #display items
10 20 33 40 50

Example 15.17, Page Number 759

In [17]:
class list:                  #*class list*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,a):                 #function to add element in array at last
        self.__arr.append(a)
        
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
    
    def op1(self,n):                       #function to return array item
        return self.__arr[n]
    
    
    
    
arr = [2,4,6,8]

theList = list()

for k in range(4):
    theList.push_back(arr[k])              #fill list with array elements
    

for iter in range(theList.begin(),theList.end(),1):
    print theList.op1(iter),                            #display the list
2 4 6 8

Example 15.18, Page Number 760

In [18]:
class list:             #*class list*#
    
    def __init__(self,a):                    #constructor
        self.__arr = [0 for j in range(a)]
   
    def op1(self,a,b):                       #change the particular item
        self.__arr[a] = b
    
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
    
    def op2(self,n):                     #function to return array element
        return self.__arr[n]
    
    
    
    
data = 0

iList = list(5)                          #empty list holds 5 ints

                                         #fill list with data
for it in range(iList.begin(),iList.end(),1):
    data += 2
    iList.op1(it,data)                   
     
                                         #display list
for it in range(iList.begin(),iList.end(),1):
    print iList.op2(it),
2 4 6 8 10

Example 15.19, Page Number 761

In [19]:
class list:             #*class list*#
    
    def __init__(self,a):                    #constructor
        self.__arr = [0 for j in range(a)]
   
    def op1(self,a,b):                       #change the particular item
        self.__arr[a] = b
    
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
    
    def find(self,a,b,c):                  #return the index of a particular element
        for j in range(a,b,1):
            if self.__arr[j] == c:
                b = j
                break
        return b
    
data = 0

theList = list(5)                         #empty list holds 5 ints

                                          #fill list with data
for it in range(theList.begin(),theList.end(),1):
    data += 2                             #2, 4, 6, 8, 10
    theList.op1(it,data)
    
                                          #look for number 8
iter = theList.find(theList.begin(),theList.end(),8)

if iter!=theList.end():
    print 'Found 8.'
    
else:
    print 'Dis not find 8.'
Found 8.

Example 15.20, Page Number 762

In [20]:
class vector:               #*class vector*#
    
    def __init__(self,a):                            #constructor
        if isinstance(a,int):
            self.__arr = [0.0 for j in range(a)]
            
        elif isinstance(a,vector):
            self.__arr = a.__arr
        
        else:
            self.__arr = a
            
    def begin(self):                       #return the first index position
        return 0
    
    def copy(self,a,b,v):                  #copy the elements of array in another vector
        for j in range(a,b,1):
            v.__arr[j-a] = self.__arr[j]
        return b-a
    
    def op1(self,n):                     #function to return array element
        return self.__arr[n]
            
        
        
        
arr = [11,13,15,17,19,21,23,25,27,29]

v1 = vector(arr)           #initialized vector
v2 = vector(10)            #uninitialized vector

print 'Enter range to be copied (Example: 2 5): '
beginRange = input("")
endRange = input("")

iter1 = v1.begin() + beginRange
iter2 = v1.begin() + endRange

iter3 = v1.copy(iter1,iter2,v2)           #copy range from v1 to v2

iter1 = v2.begin()

print 'values:',
while (iter1 != iter3):            #iteration through range in v2
    print v2.op1(iter1),           #displaying values
    iter1 += 1
Enter range to be copied (Example: 2 5): 
3
6
values: 17 19 21

Example 15.21, Page Number 763

In [21]:
class list:                  #*class list*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,a):                 #function to add element in array at last
        self.__arr.append(a)
        
    def rend(self):                        #return the first index
        return -1
    
    def rbegin(self):                      #returns the last index
        return len(self.__arr)-1
    
    def op1(self,n):                     #function to return array element
        return self.__arr[n]
    
    
    
    
arr = [2,4,6,8,10]               #array of ints

theList = list()

for j in range(5):               #transfer array to list
    theList.push_back(arr[j])
    
revit = theList.rbegin()         #reverse iterator

while (revit != theList.rend()):      #iterate backward through list,
    print theList.op1(revit),           #displaying output
    revit -= 1
10 8 6 4 2

Example 15.22, Page Number 764

In [22]:
class deque:                                #*class deque*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,a):                 #function to add element in array at last
        self.__arr.append(a)
        
    def begin(self):                       #return the first index position
        return 0
    
    def copy(self,a,b,v):                  #copy the elements of array in another vector
        for j in range(a,b,1):
            v.__arr[j] = self.__arr[j]
    
    def end(self):                         #returns the length of the array
        return len(self.__arr)
        
    def size(self):                        #reurn size of array
        self.__arr = sorted(self.__arr)    #sort the array
        return len(self.__arr)
    
    def op1(self,n):                     #function to return array element
        return self.__arr[n]
    
    
    
    
arr1 = [1,3,5,7,9]
arr2 = [2,4,6,8,10]
    
d1 = deque()
d2 = deque()

for j in range(5):                       #transfer arrays to deque
    d1.push_back(arr1[j])
    d2.push_back(arr2[j])

d1.copy(d1.begin(),d1.end(),d2)          #copy d1 to d2

for k in range(d2.size()):               #display d2
    print d2.op1(k),
1 3 5 7 9

Example 15.23, Page Number 765

In [23]:
class deque:                                #*class deque*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,a):                 #function to add element in array at last
        self.__arr.append(a)
        
    def begin(self):                       #return the first index position
        return 0
    
    def copy(self,a,b,v):                  #add one deque to another
        for j in range(a,b,1):
            v.__arr.append(self.__arr[j])
    
    def end(self):                         #returns the length of the array
        return len(self.__arr)
        
    def size(self):                        #reurn size of array
        return len(self.__arr)
    
    def op1(self,n):                     #function to return array element
        return self.__arr[n]
    
    
    
    
arr1 = [1,3,5,7,9]
arr2 = [2,4,6]
    
d1 = deque()
d2 = deque()

                                #transfer array to deques
for i in range(5):
    d1.push_back(arr1[i])
for j in range(3):
    d2.push_back(arr2[j])
    
print 'd2:',
                                #copy d1 to back of d2
d1.copy(d1.begin(),d1.end(),d2)

for k in range(d2.size()):      #display d2
    print d2.op1(k),
d2: 2 4 6 1 3 5 7 9

Example 15.24, Page Number 767

In [24]:
class list:                  #*class list*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,a):                 #function to add element in array at last
        self.__arr.append(a)
        
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
    
    def copy(self,a,b,c):
        for j in range(a,b,1):
            print self.__arr[j],c,
            
            
            
            
arr = [10,20,30,40,50]

theList = list()

for j in range(5):                    #transfer array to list
    theList.push_back(arr[j])
    
c = ","

print 'Contents of list: ',

theList.copy(theList.begin(),theList.end(),c)      #display list
Contents of list:  10 , 20 , 30 , 40 , 50 ,

Example 15.25, Page Number 768

In [25]:
class list:                  #*class list*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,a):                 #function to add element in array at last
        self.__arr.append(a)
        
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
     
    def copy(self,a,b,c):                  #write the array in the file
        for j in range(a,b,1):
            s = ''
            s += '%d' %self.__arr[j]
            c.write(s)
            
            
            
arr = [11,21,31,41,51]

theList = list()               #uninitialized list

for j in range(5):
    theList.push_back(arr[j])        #transfer array to list
    
outfile = open("ITER.TXT","w")          #open the file 

theList.copy(theList.begin(),theList.end(),outfile)        #write list to file

outfile.close()

Example 15.26, Page Number 769

In [26]:
class list:                                     #*class list*#
     
    def __init__(self,a):                       #constructor
        self.__arr = [0.0 for j in range(a)]
      
    def begin(self):                           #return the first index position
        return 0
    
    def end(self):                             #return the last index position
        return len(self.__arr)
    
    def copy(self,a,b,c):
        if isinstance(c,int):
            self.__arr = a
        
        else:
            for j in range(a,b,1):
                print self.__arr[j],c,
            
            
            
            
arr = []*5
print "Enter 5 floating numbers: "
for j in range(5):
    x = input()
    arr.append(x)

fList = list(5)                        #uninitialized list

fList.copy(arr,'end_of_stream',fList.begin())
    
c = "--"

fList.copy(fList.begin(),fList.end(),c)
Enter 5 floating numbers: 
1.1
2.2
3.3
4.4
5.5
1.1 -- 2.2 -- 3.3 -- 4.4 -- 5.5 --

Example 15.27, Page Number 770

In [27]:
class list:                  #*class list*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
    
    def copy(self,a,b,c):
        if isinstance(c,int):
            self.__arr = a
        
        else:
            for j in range(a,b,1):
                print self.__arr[j],c,

                
                
                
arr = []*5

iList = list()                      #empty list

infile = open("ITER.TXT","r")       #open a file in read mode

for j in range(5):
    arr.append(infile.read(2))      #add data from file to array 
    
iList.copy(arr,'end_of_stream',iList.begin())       #copy array to list

c = "--"

iList.copy(iList.begin(),iList.end(),c)            #display list
11 -- 21 -- 31 -- 41 -- 51 --

Example 15.28, Page Number 772

In [28]:
class set:                                  #*class set*#
    
    def __init__(self,a):                   #constructor
        self.__arr = a
        
    def insert(self,s):                     #insert the elements but without repeating
        d=1
        for j in range(len(self.__arr)):
            if s==self.__arr[j]:
                d=0
                break;
        if d==1:
            self.__arr.append(s)
            
    def erase(self,s):                      #erase a particualr item from the set
        self.__arr.remove(s)
            
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
    
    def size(self):                        #reurn size of array
        self.__arr = sorted(self.__arr)    #sort the array
        return len(self.__arr)
    
    def find(self,sn):                     #find the index of a particular element
        d=-1
        for j in range(len(self.__arr)):
            if sn==self.__arr[j]:
                d=j
                break;
        if d==-1:
            return len(self.__arr)
        else:
            return d
        
    def op1(self,n):                     #function to return array element
        return self.__arr[n]
        
        
        
        
names = ["Juanita","Robert","Mary","Amanda","Marie"]       #array of string objects

nameSet = set(names)                   #initialize set to array

nameSet.insert("Yvette")               #insert more names
nameSet.insert("Larry")
nameSet.insert("Robert")               #no effect; already in set
nameSet.insert("Barry")

nameSet.erase("Mary")                  #erase a name

print 'Size',nameSet.size()            #display size of set

iter = nameSet.begin()

while(iter != nameSet.end()-1):        #display members of set
    print nameSet.op1(iter)
    iter += 1
    
searchName = raw_input("Enter name to search for: ")        #get name from user

iter = nameSet.find(searchName)        #find matching name in set

if(iter == nameSet.end()):
    print 'The name',searchName,'is NOT in the set.'
    
else:
    print 'The name',searchName,'IS in the set.'
Size 7
Amanda
Barry
Juanita
Larry
Marie
Robert
Enter name to search for: George
The name George is NOT in the set.

Example 15.29, Page Number 774

In [29]:
class set:                                        #*class set*#
    
    def __init__(self):                         #constructor
        self.__arr = []
        
    def insert(self,s):                         #insert the element in the array
        self.__arr.append(s)
    
    def unique(self):                           #remove the duplicate items from the array
        self.__arr = sorted(self.__arr)
        a = []
        for x in self.__arr:
            if x not in a:
                a.append(x)
        self.__arr = a
        
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
    
    def op1(self,n):                     #function to return array element
        return self.__arr[n]
    
    
organic = set()                        #set of string objects

                                       #insert organic compounds
organic.insert("Curine")
organic.insert("Xanthine")
organic.insert("Curarine")
organic.insert("Melamine")
organic.insert("Cyanimide")
organic.insert("Phenol")
organic.insert("Aphrodine")
organic.insert("Imidazole")
organic.insert("Cinchonine")
organic.insert("Palmitamide")
organic.insert("Cyanimide")

organic.unique()

iter = organic.begin()

while (iter!=organic.end()):           #display set
    print organic.op1(iter)
    iter += 1
Aphrodine
Cinchonine
Curarine
Curine
Cyanimide
Imidazole
Melamine
Palmitamide
Phenol
Xanthine

Example 15.30, Page Number 776

In [30]:
class map:                                 #*class map*#
    
    def __init__(self):                    #constructor
        self.__arr1 = []                   #array for key
        self.__arr2 = []                   #array for value
        
    def op1(self,a,b):                     #add data in the arrays
        self.__arr1.append(a)
        self.__arr2.append(b)
        
    def op2(self,a):                       #return the value according to the key
        for j in range(len(self.__arr1)):
            if a==self.__arr1[j]:
                return self.__arr2[j]
            
    def sort(self):
        
        n = len(self.__arr1)
        
        for j in range(n-1):                      #outer loop
            for k in range(j+1,n,1):              #inner loop starts at outer
                
                if self.__arr1[j] > self.__arr1[k]:           #if 1st larger than 2nd
                    
                    temp = self.__arr1[j]            #swap first array
                    self.__arr1[j] = self.__arr1[k]
                    self.__arr1[k] = temp
                    
                    temp = self.__arr2[j]            #swap second array
                    self.__arr2[j] = self.__arr2[k]
                    self.__arr2[k] = temp
                    
            
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr1)
    
    def first(self,a):                     #returns the key
        return self.__arr1[a]
    
    def second(self,a):                    #returns the value
        return self.__arr2[a]
            
        
        
        
states = ["Wyoming","Colorado","Nevada","Montana","Arizona","Idaho"]
pops = [470,2890,800,787,2718,944]

mapStates = map()                   #map

for j in range(6):
    name = states[j]                #get data from array
    pop = pops[j]
    mapStates.op1(name,pop)         #put it in map
    
name = raw_input("Enter state: ")   #get state from user
pop = mapStates.op2(name)
print 'Population: %d,000' %pop     #find population
print 

mapStates.sort()

                                    #display entire map
for iter in range(mapStates.begin(),mapStates.end(),1):
    print mapStates.first(iter),'%d,000' %mapStates.second(iter) 
Enter state: Wyoming
Population: 470,000

Arizona 2718,000
Colorado 2890,000
Idaho 944,000
Montana 787,000
Nevada 800,000
Wyoming 470,000

Example 15.31, Page Number 778

In [31]:
class person:            #class person
    
    def __init__(self,lana = "blank",fina = "blank",pho = 0):          #construvtor
        self.__lastName = lana
        self.__firstName = fina
        self.__phoneNumber = pho
        
    def display(self):                                                 #display person's data
        print self.__lastName,'\t',self.__firstName,'\t\tPhone:',self.__phoneNumber
        
        
def lesst(p1,p2):                    #less than function (friend function)
    
    if p1._person__lastName == p2._person__lastName:
        if p1._person__firstName < p2._person__firstName:
            return True
        else:
            return False
        
    elif p1._person__lastName < p2._person__lastName:
        return True
    else:
        return False
    
    
def equ(p1,p2):                      #equal function (friend function)
    
    if (p1._person__lastName == p2._person__lastName) and (p1._person__firstName == p2._person__firstName):
        return True
    else:
        return False
    
    
    
    
class multiset:                                   #*class multiet*#
    
    def __init__(self):                          #constructor
        self.__arr = []
        
    def insert(self,a):                          #insert the element in the multiset
        self.__arr.append(a)
        
    def size(self):                              #return the size of multiset
        return len(self.__arr)
    
    def display(self,it):                        #display the items from multiset
        if isinstance(it,int):
            self.__arr[it].display()
            
        else:
            for j in range(len(self.__arr)):
                if equ(it,self.__arr[j]):
                    self.__arr[j].display()
        
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
    
    def count(self,sp):                    #return count of a element
        a=0
        for j in range(len(self.__arr)):
            if equ(sp,self.__arr[j]):
                a += 1
        return a
    
    
    def sort(self):
        
        n = len(self.__arr)
        
        for j in range(n-1):                      #outer loop
            for k in range(j+1,n,1):              #inner loop starts at outer
                
                if not lesst(self.__arr[j],self.__arr[k]):           #if 1st larger than 2nd
                    
                    temp = self.__arr[j]._person__lastName            #swap last name
                    self.__arr[j]._person__lastName = self.__arr[k]._person__lastName
                    self.__arr[k]._person__lastName = temp
                    
                    temp = self.__arr[j]._person__firstName            #swap firs tname
                    self.__arr[j]._person__firstName = self.__arr[k]._person__firstName
                    self.__arr[k]._person__firstName = temp
                    
                    temp = self.__arr[j]._person__phoneNumber            #swap phone number
                    self.__arr[j]._person__phoneNumber = self.__arr[k]._person__phoneNumber
                    self.__arr[k]._person__phoneNumber = temp
    
    
    
    
    
                                                #create person objects
pers1 = person("Deauville","Wiliam",8435150)
pers2 = person("McDonald","Stacey",3327563)
pers3 = person("Bartoski","peter",6946473)
pers4 = person("Kuangthu","Bruce",4157300)
pers5 = person("Wellington","John",9207404)
pers6 = person("McDonald","Amanda",8435150)
pers7 = person("Fredericks","Roger",7049982)
pers8 = person("McDonald","Stacey",7764987)

persSet = multiset()                           #multiset of persons

                                               #put persons in multiset
persSet.insert(pers1)
persSet.insert(pers2)
persSet.insert(pers3)
persSet.insert(pers4)
persSet.insert(pers5)
persSet.insert(pers6)
persSet.insert(pers7)
persSet.insert(pers8)

print 'Number of entries =',persSet.size()

persSet.sort()

iter = persSet.begin()

print
while(iter != persSet.end()):                 #display contents of multiset
    persSet.display(iter)
    iter += 1
    
                                              #get last and first name
searchLastName = raw_input("\nEnter last name of person to search for: ")
searchFirstName = raw_input("Enter first name: ")

searchPerson = person(searchLastName,searchFirstName,0)

                                              #get count of such persons
cntPersons = persSet.count(searchPerson)       
print 'Number of persons with this name =',cntPersons


persSet.display(searchPerson)                 #display all matches
Number of entries = 8

Bartoski 	peter 		Phone: 6946473
Deauville 	Wiliam 		Phone: 8435150
Fredericks 	Roger 		Phone: 7049982
Kuangthu 	Bruce 		Phone: 4157300
McDonald 	Amanda 		Phone: 8435150
McDonald 	Stacey 		Phone: 7764987
McDonald 	Stacey 		Phone: 3327563
Wellington 	John 		Phone: 9207404

Enter last name of person to search for: McDonald
Enter first name: Stacey
Number of persons with this name = 2
McDonald 	Stacey 		Phone: 7764987
McDonald 	Stacey 		Phone: 3327563

Example 15.32, Page Number 782

In [32]:
class person:                            #person class
    
    def __init__(self,lana = "blank",fina = "blank",pho = 0):           #constructor
        self.__lastName = lana
        self.__firstName = fina
        self.__phoneNumber = pho
        
    def display(self):                   #display person's data
        print self.__lastName,'\t',self.__firstName,'\t\tPhone:',self.__phoneNumber
        
    def get_phone(self):                 #return phone number
        return self.__phoneNumber
        
        
def lesst(p1,p2):                    #less than function (friend function)
    
    if p1._person__lastName == p2._person__lastName:
        if p1._person__firstName < p2._person__firstName:
            return True
        else:
            return False
        
    elif p1._person__lastName == p2._person__lastName:
        return True
    else:
        return False
    
    
def equ(p1,p2):                      #equal function (friend function)
    
    if (p1._person__lastName == p2._person__lastName) and (p1._person__firstName == p2._person__firstName):
        return True
    else:
        return False
    
def notequ(p1,p2):                    #not equal function (friend function)
    return not(equ(p1,p2))

def greatert(p1,p2):                  #greater than function (friend function)
    return not(lesst(p1,p2)) and not(equ(p1,p2))





class list:                                 #*class list*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,pe):                 #function to add element in array at last
        self.__arr.append(pe)
        
    def size(self):                         #return the size of list
        return len(self.__arr)
    
    def display(self,it):                   #display the element of list
        if isinstance(it,int):
            self.__arr[it].display()
            
        else:
            for j in range(len(self.__arr)):
                if equ(it,self.__arr[j]):
                    self.__arr[j].display()
        
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
    
    def find(self,sp):                     #find the index of a particular item
        for j in range(len(self.__arr)):
            if equ(sp,self.__arr[j]):
                return j
    
    def display1(self,sn):                 #display the elements according to the phone number
        for j in range(len(self.__arr)):
            if sn==self.__arr[j].get_phone():
                self.__arr[j].display()

                
                
                
                
persList = list()                    #list of persons

                                     #put persons in list
persList.push_back(person("Deauville","Wiliam",8435150))
persList.push_back(person("McDonald","Stacey",3327563))
persList.push_back(person("Bartoski","peter",6946473))
persList.push_back(person("Kuangthu","Bruce",4157300))
persList.push_back(person("Wellington","John",9207404))
persList.push_back(person("McDonald","Amanda",8435150))
persList.push_back(person("Fredericks","Roger",7049982))
persList.push_back(person("McDonald","Stacey",7764987))

print 'Number of entries =',persList.size()

iter = persList.begin()

print
while(iter != persList.end()):       #display contents of list
    persList.display(iter)
    iter += 1
    
    
#find person with specified name (last and first)
searchLastName = raw_input("\nEnter last name of person to search for: ")
searchFirstName = raw_input("Enter first name: ")

searchPerson = person(searchLastName,searchFirstName,0)        #make a person with that name

                                                    #search for first match of name
iter1 = persList.find(searchPerson)
print 'Person(s) with the same name is(are)'

persList.display(searchPerson)


#find person with specified phone number
sNumber = input("\nEnter phone nnumber (format 1234567): ")
print 'Person(s) with the same name is(are)'

persList.display1(sNumber)            #display the match 
Number of entries = 8

Deauville 	Wiliam 		Phone: 8435150
McDonald 	Stacey 		Phone: 3327563
Bartoski 	peter 		Phone: 6946473
Kuangthu 	Bruce 		Phone: 4157300
Wellington 	John 		Phone: 9207404
McDonald 	Amanda 		Phone: 8435150
Fredericks 	Roger 		Phone: 7049982
McDonald 	Stacey 		Phone: 7764987

Enter last name of person to search for: Wellington
Enter first name: John
Person(s) with the same name is(are)
Wellington 	John 		Phone: 9207404

Enter phone nnumber (format 1234567): 8435150
Person(s) with the same name is(are)
Deauville 	Wiliam 		Phone: 8435150
McDonald 	Amanda 		Phone: 8435150

Example 15.33, Page Number 787

In [33]:
class airtime:
    
    def __init__(self,h=0,m=0):
        self.__hours = h                     # 0 to 23
        self.__minutes = m                   # 0 to 59
        
    def display(self):                       #output to screen
        print self.__hours,':',self.__minutes
        
    def get(self):                           #input from user
        print 'Enter airtime (format 12:59):'
        self.__hours = input()
        self.__dummy = raw_input()
        self.__minutes = input()
        
    def __iadd__(self,right):                #overloaded + operator
        temph = self.__hours + right.__hours
        tempm = self.__minutes + right.__minutes
        
        if tempm>=60:
            temph =temph + 1
            tempm =tempm - 60
            
        return airtime(temph,tempm)
    
    
    
class list:                                 #*class list*#
    
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,te):                 #function to add element in array at last
        self.__arr.append(te)
        
    def accumulate(self,a,b,c):             #sum all the airtime
        for j in range(b):
            c += self.__arr[j]
        return c
    
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
    

    
    
    
sum = airtime()
airlist = list()

while True:
    temp = airtime()
    temp.get()                              #get airtime from user
    airlist.push_back(temp)
    answer = raw_input("enter another (y/n)? ")
    
    if(answer=='n'):
        break;
        
sum = airlist.accumulate(airlist.begin(),airlist.end(),airtime(0,0))          #sum all the airtimes

print '\n\nsum =',
sum.display()             #display sum
Enter airtime (format 12:59):
3
:
45
enter another (y/n)? y
Enter airtime (format 12:59):
5
:
10
enter another (y/n)? y
Enter airtime (format 12:59):
2
:
25
enter another (y/n)? y
Enter airtime (format 12:59):
0
:
55
enter another (y/n)? n


sum = 12 : 15

Example 15.34, Page Number 790

In [34]:
class person:             #class person
    
    def __init__(self,lana = "blank",fina = "blank",pho = 0):         #constructor
        self.__lastName = lana
        self.__firstName = fina
        self.__phoneNumber = pho
        
    def display(self):            #display person's data
        print self.__lastName,'\t',self.__firstName,'\t\tPhone:',self.__phoneNumber
        
    def get_lastname(self):       #return last name
        return self.__lastName

        
def lesst(p1,p2):                    #less than function (friend function)
    
    if p1._person__lastName == p2._person__lastName:
        if p1._person__firstName < p2._person__firstName:
            return True
        else:
            return False
        
    elif p1._person__lastName == p2._person__lastName:
        return True
    else:
        return False
    
def equ(p1,p2):                      #equal function (friend function)
    if (p1._person__lastName == p2._person__lastName) and (p1._person__firstName == p2._person__firstName):
        return True
    else:
        return False
    
    
    
class vector:                             #*class vector*#
     
    def __init__(self):                    #constructor
        self.__arr = []
        
    def push_back(self,te):                 #function to add element in array at last
        self.__arr.append(te)                    
    
    def begin(self):                       #return the first index position
        return 0
    
    def end(self):                         #return the last index position
        return len(self.__arr)
    
    def display(self,a,b):                  #display the vector element 
        for j in range(a,b,1):
            self.__arr[j].display()
    
    def sort(self):
        
        n = len(self.__arr)
        
        for j in range(n-1):                      #outer loop
            for k in range(j+1,n,1):              #inner loop starts at outer
                
                if not lesst(self.__arr[j],self.__arr[k]):           #if 1st larger than 2nd
                    
                    temp = self.__arr[j]._person__lastName            #swap last name
                    self.__arr[j]._person__lastName = self.__arr[k]._person__lastName
                    self.__arr[k]._person__lastName = temp
                    
                    temp = self.__arr[j]._person__firstName            #swap firstname
                    self.__arr[j]._person__firstName = self.__arr[k]._person__firstName
                    self.__arr[k]._person__firstName = temp
                    
                    temp = self.__arr[j]._person__phoneNumber            #swap phone number
                    self.__arr[j]._person__phoneNumber = self.__arr[k]._person__phoneNumber
                    self.__arr[k]._person__phoneNumber = temp
    
    
    

vectPtrspers = vector()                         #vector object

#make persons
ptrp1 = person("Kuangthu","Bruce",4157300)
ptrp2 = person("Deauville","Wiliam",8435150)
ptrp3 = person("Wellington","John",9207404)
ptrp4 = person("Bartoski","peter",6946473)
ptrp5 = person("Fredericks","Roger",7049982)
ptrp6 = person("McDonald","Stacey",7764987)

#put persons in set
vectPtrspers.push_back(ptrp1)
vectPtrspers.push_back(ptrp2)
vectPtrspers.push_back(ptrp3)
vectPtrspers.push_back(ptrp4)
vectPtrspers.push_back(ptrp5)
vectPtrspers.push_back(ptrp6)

vectPtrspers.display(vectPtrspers.begin(),vectPtrspers.end())          #display vector

print '\nsorted pointers '
vectPtrspers.display(vectPtrspers.begin(),vectPtrspers.end())

vectPtrspers.sort()
print '\nsorted persons '
vectPtrspers.display(vectPtrspers.begin(),vectPtrspers.end())
Kuangthu 	Bruce 		Phone: 4157300
Deauville 	Wiliam 		Phone: 8435150
Wellington 	John 		Phone: 9207404
Bartoski 	peter 		Phone: 6946473
Fredericks 	Roger 		Phone: 7049982
McDonald 	Stacey 		Phone: 7764987

sorted pointers 
Kuangthu 	Bruce 		Phone: 4157300
Deauville 	Wiliam 		Phone: 8435150
Wellington 	John 		Phone: 9207404
Bartoski 	peter 		Phone: 6946473
Fredericks 	Roger 		Phone: 7049982
McDonald 	Stacey 		Phone: 7764987

sorted persons 
McDonald 	Stacey 		Phone: 7764987
Fredericks 	Roger 		Phone: 7049982
Bartoski 	peter 		Phone: 6946473
Wellington 	John 		Phone: 9207404
Deauville 	Wiliam 		Phone: 8435150
Kuangthu 	Bruce 		Phone: 4157300
In [ ]: