Chapter 21: Introducing the Standard Template Library

Example 21.1, Page Number:507

In [1]:
 
v=[]                 #Create a zero length vector
 
print "Size =",len(v)
 

for i in range(10):
    v.append(i)
    
#display current size of v
print "Current contents: "
print "Size now =",len(v)

#display contents of vector
for i in range(len(v)):
    print v[i],
    
print
    
#put more values onto end of vector
#again, vector will grow as needed.
for i in range(10):
    v.append(i+10)
#display current size of v
print "Size now =",len(v)

#display contents of vector
print "Current contents:"
for i in range(len(v)):
    print v[i],
print
    
#change contents of vector
for i in range(len(v)):
    v[i]=v[i]+v[i]
    
#display contents of vector
print "Contents doubled:"
for i in range(len(v)):
    print v[i],
Size = 0
Current contents: 
Size now = 10
0 1 2 3 4 5 6 7 8 9
Size now = 20
Current contents:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Contents doubled:
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38

Example 21.2, Page Number:508

In [2]:
#Variable declaration
v=[]                 #Create a zero length vector

#put values onto end of vector
for i in range(10):
    v.append(chr(ord('A')+i))
    
#can access vector contents using subscripts
for i in range(len(v)):
    print v[i],   
print
    
#access via iterator
for p in v:
    print p,
    
A B C D E F G H I J
A B C D E F G H I J

Example 21.3, Page Number:509

In [3]:
#Variable declaration
v=[]                 #Create a zero length vector

#put values onto end of vector
for i in range(10):
    v.append(chr(ord('A')+i))
    
#Display original contents of vector
print "Size =",len(v)
print "Original contents:"
for i in range(len(v)):
    print v[i],   
print "\n"
    
p=2                 #point to 3rd element
for i in range(10):
    v.insert(p+i,'X')
    
#display contents after insertion
print "Size after insert =",len(v)
print "Contents after insert:"
for i in range(len(v)):
    print v[i],
print "\n"

#remove those elements
p=2                #point to 3rd element
for i in range(10):
    v.pop(p)
    
#display contents after insertion
print "Size after erase =",len(v)
print "Contents after insert:"
for i in range(len(v)):
    print v[i],
Size = 10
Original contents:
A B C D E F G H I J 

Size after insert = 20
Contents after insert:
A B X X X X X X X X X X C D E F G H I J 

Size after erase = 10
Contents after insert:
A B C D E F G H I J

Example 21.4, Page Number:511

In [4]:
class three_d:
    def __init__(self,a,b,c):   #3D coordinates
        self.x=a
        self.y=b
        self.z=c
    #Display x,y,z coordinates - three_d inserter.
    def __repr__(self):
        return str(self.x)+", "+str(self.y)+", "+str(self.z)+"\n"
    def __add__(self,a):
        self.x+=a
        self.y+=a
        self.z+=a
        return self
    def __lt__(self,b):
        return (self.x+self.y+self.z)<(b.x+b.y+b.z)
    def __eq__(self,b):
        return (self.x+self.y+self.z)==(b.x+b.y+b.z) 
    
#Variable declaration
v=[]

#add objects to the vector
for i in range(10):
    v.append(three_d(i,i+2,i-3))
    
#Display contents of vector
for i in range(len(v)):
    print v[i],   
print


#Modify objects in a vector
for i in range(len(v)):
    v[i]=v[i]+10  

#Display modified vector
for i in range(len(v)):
    print v[i],   
0, 2, -3
 1, 3, -2
 2, 4, -1
 3, 5, 0
 4, 6, 1
 5, 7, 2
 6, 8, 3
 7, 9, 4
 8, 10, 5
 9, 11, 6

10, 12, 7
 11, 13, 8
 12, 14, 9
 13, 15, 10
 14, 16, 11
 15, 17, 12
 16, 18, 13
 17, 19, 14
 18, 20, 15
 19, 21, 16

Example 21.5, Page Number:513

In [5]:
 
v=[]
v2=[]

for i in range(10):
    v.append(chr(ord('A')+i))
    
#Display original contents of vector
print "Size =",len(v)
print "Original contents:"
for i in range(len(v)):
    print v[i],   
print "\n"

#initialze second vector
str="-STL Power-"
for i in range(len(str)):
    v2.append(str[i])
 
#get iterators to the middle of v and to the start and end of v2.
p=5
p2start=0
p2end=len(v2)-1

#insert v2 into v
for i in range(p2end):
    v.insert(p+i,v2[p2start+i])
    
#display result
print "Contents of v after inserton:"
for i in range(len(v)):
    print v[i],
    
Size = 10
Original contents:
A B C D E F G H I J 

Contents of v after inserton:
A B C D E - S T L   P o w e r F G H I J

Example 21.6, Page Number:517

In [6]:
#Variable declaration
lst=[]                     #create an empty list

for i in range(10):
    lst.append(chr(ord('A')+i))
    
print "Size =",len(lst)

print "Contents:",
for p in lst:
    print p,   
print "\n"
Size = 10
Contents: A B C D E F G H I J 

Example 21.7, Page Number:518

In [8]:
#Variable declaration
lst=[]                     
revlst=[]

for i in range(10):
    lst.append(chr(ord('A')+i))
    
print "Size of list =",len(lst)

print "Original Contents:",
#Remove elements from lst and put them into revlst in reverse order.
for p in lst:
    print p,  
    revlst.insert(0,p) 
for i in range(10):
    lst.pop(0)
print "\n"

print "Size of revlst =",len(revlst)

print "Reversed Contents:",
for p in revlst:
    print p,
Size of list = 10
Original Contents: A B C D E F G H I J 

Size of revlst = 10
Reversed Contents: J I H G F E D C B A

Example 21.8, Page Number:519

In [9]:
import random

#Variable declaration
lst=[]                     

#create a list of random integers
for i in range(10):
    lst.append(random.randint(0,100))

print "Original Contents:",
for p in lst:
    print p,  
print "\n"

#sort the list
lst.sort()

print "Sorted Contents:",
for p in lst:
    print p,
Original Contents: 75 73 72 4 88 7 85 21 67 42 

Sorted Contents: 4 7 21 42 67 72 73 75 85 88

Example 21.9, Page Number:520

In [10]:
#Variable declaration
lst1=[]                     
lst2=[]

for i in xrange(0,10,2):
    lst1.append(chr(ord('A')+i))
for i in xrange(1,11,2):
    lst2.append(chr(ord('A')+i))

print "Contents of lst1:",
for p in lst1:
    print p,  
print "\n"

print "Contents of lst2:",
for p in lst2:
    print p,  
print "\n"

#merge the lists
lst1=lst1+lst2
lst1.sort()
lst2=[]

if lst2==[]:
    print "lst2 is now empty"

print "Contentsof lst1 after merge:"
for p in lst1:
    print p,
Contents of lst1: A C E G I 

Contents of lst2: B D F H J 

lst2 is now empty
Contentsof lst1 after merge:
A B C D E F G H I J

Example 21.10, Page Number:521

In [12]:
class myclass:
    def __init__(self,i=0,j=0):
        self.__a=i
        self.__b=j
        self.sum=self.__a+self.__b
    def getsum(self):
        return self.sum
    def __lt__(self,o2):
        return self.sum<o2.sum
    def __gt__(self,o2):
        return self.sum>o2.sum
    def __eq__(self,o2):
        return self.sum==o2.sum
    def __ne__(self, other):
        return not self.__eq__(self)
        
#create first list
lst1=[]
for i in range(10):
    lst1.append(myclass(i,i))
               
print "First list:",
for p in lst1:
    print p.getsum(),
print

#create second list
lst2=[]
for i in range(10):
    lst2.append(myclass(i*2,i*3))
               
print "First list:",
for p in lst2:
    print p.getsum(),
print
    
#Now merge list
lst1=lst1+lst2
lst1.sort()

#Display merge list
print "Merged list:",
for p in lst1:
    print p.getsum(),
print
First list: 0 2 4 6 8 10 12 14 16 18
First list: 0 5 10 15 20 25 30 35 40 45
Merged list: 0 0 2 4 5 6 8 10 10 12 14 15 16 18 20 25 30 35 40 45

Example 21.11, Page Number:527

In [13]:
#Variable declaration
m=[]             

#define the function find
def find(x,ch):
    for p in x:
        if p[0]==ch:
            return p
    return -1

#put pairs into map
for i in range(10):
    m.append([chr(ord('A')+i),i])
 
#User Input
ch='D'

#find value of the given key
p=find(m,ch)

if not(p==-1):
    print p[1]
else:
    print "Key not in the map"
3

Example 21.12, Page Number:528

In [14]:
 
def find(x,ch):
    for p in x:
        if p[0].get()==ch.get():
            return p
    return -1


class word:
    def __init__(self,s=""):
        self.str=s
    def get(self):
        return self.str
    #must define less than relative to word objects
    def __lt__(self,b):
        return self.str<b.str

class meaning:
    def __init__(self,s=""):
        self.str=s
    def get(self):
        return self.str

dictionary=[]

dictionary.append([word("house"),meaning("A place of dwelling")])
dictionary.append([word("keyboard"),meaning("An input device")])
dictionary.append([word("programming"),meaning("The act of writing a program")])
dictionary.append([word("STL"),meaning("Standard Template Library")])

#given a word, find meaning
print "Enter word:"
str="house"        #User input

p=find(dictionary,word(str))

if not(p==-1):
    print "Definition:",p[1].get()
else:
    print "Word not in the dictionary."
Enter word:
Definition: A place of dwelling

Example 21.13, Page Number:532

In [15]:
def isvowel(ch):
    ch=ch.lower()
    if (ch=='a' or ch=='e'or ch=='i' or ch=='o' or ch=='u'):
        return 1
    else:
        return 0

str="STL programming is powerful."
v=[]

for i in range(len(str)):
    v.append(str[i])
    
print "Sequence:",
for i in range(len(v)):
    print v[i],
print

n=str.count('p')
print n,"characters are p"

#count if vowel
n=0
for i in v:
    if isvowel(i):
        n+=1
    
print n,"characters are vowels."
Sequence: S T L   p r o g r a m m i n g   i s   p o w e r f u l .
2 characters are p
7 characters are vowels.

Example 21.14, Page Number:534

In [16]:
str="This is a test"
v=[]
v2=[]

for i in range(len(str)):
    v.append(str[i])
    
# ***implement remove_copy***
print "Input sequence:",
for i in range(len(v)):
    print v[i],
print 

#Remove all i's
v2 = str.replace("i", "")

print "Result after removing i's: ",
print v2,"\n"


# ***implement replace_copy***
print "Input sequence:",
for i in range(len(v)):
    print v[i],
print 

#Replace s's with X's
v2 = str.replace("s", "X")

print "Result after replacning s's with X's: ",
print v2
Input sequence: T h i s   i s   a   t e s t
Result after removing i's:  Ths s a test 

Input sequence: T h i s   i s   a   t e s t
Result after replacning s's with X's:  ThiX iX a teXt

Example 21.15, Page Number:535

In [17]:
 
v=[]

for i in range(10):
    v.append(i)
    
print "Initial:",
for i in range(len(v)):
    print v[i],
print

#Reversing the list
v.reverse()

print "Reversed:",
for i in range(len(v)):
    print v[i],
print    
    
Initial: 0 1 2 3 4 5 6 7 8 9
Reversed: 9 8 7 6 5 4 3 2 1 0

Example 21.16, Page Number:536

In [18]:
 
def xform(i):
    return i*i   #square original value

#the transorm function
def transform(x,f):
    for i in range(len(x)):
        x[i]= f(x[i])
        
#Variable declaration
x1=[]

#put values into list
for i in range(10):
    x1.append(i)

print "Original contents of x1: ",
for p in x1:
    print p,
print 

#transform x1
p=transform(x1,xform)

print "Transformed contents of x1:",
for p in x1:
    print p,
Original contents of x1:  0 1 2 3 4 5 6 7 8 9
Transformed contents of x1: 0 1 4 9 16 25 36 49 64 81

Example 21.17, Page Number:540

In [19]:
str1="The string class gives "
str2="C++ high strng handlng."

#assign a string
str3=str1
print str1,"\n",str3

#Concatenate two strings
str3=str1+str2
print str3

#Compare strings
if str3>str1:
    print "str3 > str1"
if str3==str1+str2:
    print "str3 == str1+str2"
    
str1="This is a null-terminated string."
print str1

#create a string object using another string object
str4=str1
print str4

#nput a string
print "Enter a string:"
str4="Hello"
print str4
The string class gives  
The string class gives 
The string class gives C++ high strng handlng.
str3 > str1
str3 == str1+str2
This is a null-terminated string.
This is a null-terminated string.
Enter a string:
Hello

Example 21.18, Page Number:542

In [21]:
str1="This is a test"
str2="ABCDEFG"

print "Initial strings:"
print "str1:",str1
print "str2:",str2
print

#demonstrate insert
print "Insert str2 into str1:"
str1=str1[:5]+str2+str1[5:]
print str1,"\n"

#demonstrate erase
print "Remove 7 charecters from str1:"
str1=str[:5]+str[5:]
print str1,"\n"

#demonstrate replace
print "Replace 2 characters in str1 with str2:"
str1=str1[:5]+str2+str1[7:]
print str1
Initial strings:
str1: This is a test
str2: ABCDEFG

Insert str2 into str1:
This ABCDEFGis a test 

Remove 7 charecters from str1:
This is a test 

Replace 2 characters in str1 with str2:
This ABCDEFG a test

Example 21.19, Page Number:543

In [22]:
import string

#Variable declaration 
s1="The string class makes string handling easy."

i=string.find(s1,"class")
if not(i==-1):
    print "Match found at",i
    print "Remaining string is:",
    s2=s1[i:]
    print s2
Match found at 11
Remaining string is: class makes string handling easy.

Example 21.20, Page Number:545

In [23]:
 
def find(x,ch):
    for p in x:
        if p[0]==ch:
            return p
    return -1


dictionary=[]

dictionary.append(["house","A place of dwelling"])
dictionary.append(["keyboard","An input device"])
dictionary.append(["programming","The act of writing a program"])
dictionary.append(["STL","Standard Template Library"])

#given a word, find meaning
print "Enter word:"
str="house"        #User input

p=find(dictionary,str)

if not(p==-1):
    print "Definition:",p[1]
else:
    print "Word not in the dictionary."
Enter word:
Definition: A place of dwelling
In [ ]: