# Chapter 16-Generic Programming with Templates¶

## Example-mswap.cpp, Page no-647¶

In [1]:
def swap(x, y): #function overloading
t=x
x=y
y=t
return x, y
ch1, ch2=[str(x) for x in raw_input("Enter two characters <ch1, ch2>: ").split()]
ch1, ch2 = swap(ch1, ch2)
print "On swapping <ch1, ch2>:", ch1, ch2
a, b=[int(x) for x in raw_input("Enter two characters <a, b>: ").split()]
a, b = swap(a, b)
print "On swapping <a, b>:", a,b
c, d=[float(x) for x in raw_input("Enter two floats <c, d>: ").split()]
c, d = swap(c, d)
print "On swapping <c, d>:", c, d

Enter two characters <ch1, ch2>: R K
On swapping <ch1, ch2>: K R
Enter two characters <a, b>: 5 10
On swapping <a, b>: 10 5
Enter two floats <c, d>: 20.5 99.5
On swapping <c, d>: 99.5 20.5


## Example-gswap.cpp, Page no-650¶

In [2]:
def swap(x, y):
t=x
x=y
y=t
return x, y
ch1, ch2=[str(x) for x in raw_input("Enter two characters <ch1, ch2>: ").split()]
ch1, ch2 = swap(ch1, ch2)
print "On swapping <ch1, ch2>:", ch1, ch2
a, b=[int(x) for x in raw_input("Enter two characters <a, b>: ").split()]
a, b = swap(a, b)
print "On swapping <a, b>:", a,b
c, d=[float(x) for x in raw_input("Enter two floats <c, d>: ").split()]
c, d = swap(c, d)
print "On swapping <c, d>:", c, d

Enter two characters <ch1, ch2>: R K
On swapping <ch1, ch2>: K R
Enter two characters <a, b>: 5 10
On swapping <a, b>: 10 5
Enter two floats <c, d>: 20.5 99.5
On swapping <c, d>: 99.5 20.5


## Example-max1.cpp, Page no-651¶

In [5]:
def Max(a, b):
if a>b:
return a
else:
return b
ch1, ch2=[str(x) for x in raw_input("Enter two characters <ch1, ch2>: ").split()]
ch = Max(ch1, ch2)
print "max( ch1, ch2 ):", ch
a, b=[int(x) for x in raw_input("Enter two characters <a, b>: ").split()]
c = Max(a, b)
print "max( a, b ):", c
f1, f2=[float(x) for x in raw_input("Enter two floats <f1, f2>: ").split()]
f3 = Max(f1, f2)
print "max( f1, f2 ):", f3

Enter two characters <ch1, ch2>: A B
max( ch1, ch2 ): B
Enter two characters <a, b>: 20 10
max( a, b ): 20
Enter two floats <f1, f2>: 20.5 30.9
max( f1, f2 ): 30.9


## Example-max2.cpp, Page no-653¶

In [1]:
def Max(a, b):
if a>b:
return a
else:
return b
ch1, ch2=[str(x) for x in raw_input("Enter two characters <ch1, ch2>: ").split()]
ch = Max(ch1, ch2)
print "max( ch1, ch2 ):", ch
a, b=[int(x) for x in raw_input("Enter two characters <a, b>: ").split()]
c = Max(a, b)
print "max( a, b ):", c
str1, str2=raw_input("Enter two strings <str1, str2>: ").split()
print "max( str1, str2 ):", Max(str1, str2)

Enter two characters <ch1, ch2>: A Z
max( ch1, ch2 ): Z
Enter two characters <a, b>: 5 6
max( a, b ): 6
Enter two strings <str1, str2>: Tejaswi Rajkumar
max( str1, str2 ): Tejaswi


## Example-bsort.cpp, Page no-654¶

In [1]:
[false, true]=[0, 1]
type=['false', 'true']
t=x
x=y
y=t
return x, y
def BubbleSort(SortData, Size):
swapped=true
for i in range(Size-1):
if swapped==true:
swapped=false
for j in range((Size-1)-i):
if SortData[j]>SortData[j+1]:
swapped=true
SortData[j], SortData[j+1]=swap(SortData[j], SortData[j+1])
IntNums=[int]*25
FloatNums=[float]*25
print "Program to sort elements..."
#Integer numbers sorting
size=int(raw_input("Enter the size of the integer vector <max-25>:"))
print "Enter the elements of the integer vector..."
for i in range(size):
IntNums[i]=int(raw_input())
BubbleSort(IntNums, size)
print "Sorted Vector:"
for i in range(size):
print IntNums[i],
#Floating point numbers sorting
size=int(raw_input("Enter the size of the float vector <max-25>:"))
print "Enter the elements of the float vector..."
for i in range(size):
FloatNums[i]=float(raw_input())
BubbleSort(FloatNums, size)
print "Sorted Vector:"
for i in range(size):
print FloatNums[i],

Program to sort elements...
Enter the size of the integer vector <max-25>:4
Enter the elements of the integer vector...
8
4
1
6
Sorted Vector:
1 4 6 8Enter the size of the float vector <max-25>:3
Enter the elements of the float vector...
8.5
3.2
8.9
Sorted Vector:
3.2 8.5 8.9


## Example-tprint.cpp, Page no-656¶

In [2]:
def Print(data, nTimes=None):
if isinstance(nTimes, int):
for i in range(nTimes):
print data
else:
print data
Print(1)
Print(1.5)
Print(520, 2)
Print("OOP is Great", 3)

1
1.5
520
520
OOP is Great
OOP is Great
OOP is Great


## Example-bsearch.cpp, Page no-658¶

In [4]:
[false, true]=[0, 1]
type=['false', 'true']
def RecBinSearch(Data, SrchElem, low, high):
if low>high:
return -1
mid=int((low+high)/2)
if SrchElem<Data[mid]:
return RecBinSearch(Data, SrchElem, low, mid-1)
elif SrchElem>Data[mid]:
return RecBinSearch(Data, SrchElem, mid+1, high)
return mid
num=[int]*25
FloatNums=[float]*25
print "Program to search integer elements..."
size=int(raw_input("How many elements ? "))
print "Enter the elements in ascending order for binary search..."
for i in range(size):
num[i]=int(raw_input())
elem=int(raw_input("Enter the element to be searched: "))
index=RecBinSearch(num, elem, 0, size)
if index==-1:
else:
print "Element", elem, "found at position", index

Program to search integer elements...
How many elements ? 4
Enter the elements in ascending order for binary search...
1
4
6
8
Enter the element to be searched: 6
Element 6 found at position 2


## Example-student.cpp, Page no-661¶

In [1]:
from ctypes import Structure
class stuRec(Structure):
name=str
age=int
collegeCode=str
def Display(t):
print t
def output(s):
print "Name:", s.name
print "Age:", s.age
print "College Code:", s.collegeCode
s1=stuRec()
print "Enter student record details..."
s1.name=raw_input("Name: ")
s1.age=int(raw_input("Age: "))
s1.collegeCode=raw_input("College Code: ")
print "The student record:"
print "Name:",
Display(s1.name)
print "Age:",
Display(s1.age)
print "College Code:",
Display(s1.collegeCode)
print "The student record:"
output(s1)

Enter student record details...
Name: Chinamma
Age: 18
College Code: A
The student record:
Name: Chinamma
Age: 18
College Code: A
The student record:
Name: Chinamma
Age: 18
College Code: A


## Example-vector.cpp, Page no-665¶

In [1]:
class vector:
__size=int
def __init__(self, vector_size):
self.__size=vector_size
self.__v=[vector]*self.__size
def __del__(self):
del self.__v
def elem(self, i, x=None):
if isinstance(x, int) or isinstance(x, float):
if i>=self.__size:
print "Error: Out of Range"
return
self.__v[i]=x
else:
return self.__v[i]
def show(self):
for i in range(self.__size):
print self.elem(i), ",",
int_vect=vector(5)
float_vect=vector(4)
for i in range(5):
int_vect.elem(i, i+1)
for i in range(4):
float_vect.elem(i,i+1.5)
print "Integer Vector:",
int_vect.show()
print "\nFloating Vector:",
float_vect.show()

Integer Vector: 1 , 2 , 3 , 4 , 5 ,
Floating Vector: 1.5 , 2.5 , 3.5 , 4.5 ,


## Example-union.cpp, Page no-670¶

In [3]:
(false, true)=(0, 1) #enum type
type =['false', 'true']
MAX_ITEMS=25
def IsExist(self, item):
for i in range(self._Bag__ItemCount):
if self._Bag__contents[i]==item:
return true
return false
def show(self):
for i in range(self._Bag__ItemCount):
print self._Bag__contents[i],
print ""
class Bag:
#protected members
__ItemCount=int
def __init__(self):
self.__ItemCount=0
self.__contents=[int]*MAX_ITEMS
def put(self, item):
self.__contents[self.__ItemCount]=item
self.__ItemCount+=1
def IsEmpty(self):
return true if self.__ItemCount==0 else false
def IsFull(self):
return true if self.__ItemCount==MAX_ITEMS else false
IsExist=IsExist
show=show
while(true):
element=int(raw_input("Enter Set Element <0-end>: "))
if element==0:
break
temp = Set()
temp=s1
for i in range(s2._Bag__ItemCount):
if s1.IsExist(s2._Bag__contents[i])==false:
return temp
class Set(Bag):
if(self.IsExist(element)==false and self.IsFull()==false):
self.put(element)
def __assign__(self, s2):
for i in range(s2._Bag__ItemCount):
self.__contents[i]=s2.__contents[i]
self.__ItemCount=s2.__ItemCount
s1=Set()
s2=Set()
s3=Set()
print "Enter Set 1 elements.."
print "Enter Set 2 elemets.."
s3=s1+s2
print "Union of s1 and s2 : ",
s3.show()

Enter Set 1 elements..
Enter Set Element <0-end>: 1
Enter Set Element <0-end>: 2
Enter Set Element <0-end>: 3
Enter Set Element <0-end>: 4
Enter Set Element <0-end>: 0
Enter Set 2 elemets..
Enter Set Element <0-end>: 2
Enter Set Element <0-end>: 4
Enter Set Element <0-end>: 5
Enter Set Element <0-end>: 6
Enter Set Element <0-end>: 0
Union of s1 and s2 :  1 2 3 4 5 6


## Example-tree.cpp, Page no-673¶

In [1]:
class TreeNode:
def __init__(self, dataIn, l, r):
if isinstance(l, TreeNode):
self.__left=l
self.__right=r
else:
self.__left=None
self.__right=None
self.__data=dataIn
class BinaryTree:
__root=None
def InsertNode(self, tree, data):
if tree==None:
tree=TreeNode(data, None, None)
return tree
if data<tree._TreeNode__data:
tree._TreeNode__left=self.InsertNode(tree._TreeNode__left, data)
elif data>tree._TreeNode__data:
tree._TreeNode__right=self.InsertNode(tree._TreeNode__right, data)
return tree
def PrintTreeTriangle(self, tree, level):
if tree:
self.PrintTreeTriangle(tree._TreeNode__right, level+1)
for i in range(level):
print "\t",
print "%g" %tree._TreeNode__data
self.PrintTreeTriangle(tree._TreeNode__left, level+1)
def PrintTreeDiagonal(self, tree, level):
if tree!=None:
for i in range(level):
print "\t",
print "%g" %tree._TreeNode__data
self.PrintTreeTriangle(tree._TreeNode__left, level+1)
self.PrintTreeTriangle(tree._TreeNode__right, level+1)
def PreOrderTraverse(self, tree):
if tree:
print "%g" %tree._TreeNode__data,
self.PreOrderTraverse(tree._TreeNode__left)
self.PreOrderTraverse(tree._TreeNode__right)
def InOrderTraverse(self, tree):
if tree:
self.InOrderTraverse(tree._TreeNode__left)
print "%g" %tree._TreeNode__data,
self.InOrderTraverse(tree._TreeNode__right)
def PostOrderTraverse(self, tree):
if tree:
self.PostOrderTraverse(tree._TreeNode__left)
self.PostOrderTraverse(tree._TreeNode__right)
print "%g" %tree._TreeNode__data,
def SearchTree(self, tree, data):
while(tree):
if data<tree._TreeNode__data:
tree=tree._TreeNode__left
elif data>tree._TreeNode__data:
tree=tree._TreeNode__right
else:
return tree
return None
def PreOrder(self):
self.PreOrderTraverse(self.__root)
def InOrder(self):
self.InOrderTraverse(self.__root)
def PostOrder(self):
self.PostOrderTraverse(self.__root)
def PrintTree(self, disptype):
if disptype==1:
self.PrintTreeTriangle(self.__root, 1)
else:
self.PrintTreeDiagonal(self.__root, 1)
def Insert(self, data):
self.__root=self.InsertNode(self.__root, data)
def Search(self, data):
return self.SearchTree(self.__root, data)
btree=BinaryTree()
print "This Program Demonstrates the Binary Tree Operations"
disptype=int(raw_input("Tree Diplay Style: [1] - Triangular [2] - Diagonal form: "))
print "Tree creation process..."
while 1:
data=float(raw_input("Enter node number to be inserted <0-END>: "))
if data==0:
break
btree.Insert(data)
print "Binary Tree is..."
btree.PrintTree(disptype)
print "Pre-Order Traversal:",
btree.PreOrder()
print "\nIn-Order Traversal:",
btree.InOrder()
print "\nPost-Order Traversal:",
btree.PostOrder()
print ""
print "Tree search process..."
while(1):
data=float(raw_input("Enter node number to be inserted <0-END>: "))
if data==0:
break
if btree.Search(data):
print "Found data in the Tree"
else:

This Program Demonstrates the Binary Tree Operations
Tree Diplay Style: [1] - Triangular [2] - Diagonal form: 1
Tree creation process...
Enter node number to be inserted <0-END>: 5
Binary Tree is...
5
Pre-Order Traversal: 5
In-Order Traversal: 5
Post-Order Traversal: 5
Enter node number to be inserted <0-END>: 3
Binary Tree is...
5
3
Pre-Order Traversal: 5 3
In-Order Traversal: 3 5
Post-Order Traversal: 3 5
Enter node number to be inserted <0-END>: 8
Binary Tree is...
8
5
3
Pre-Order Traversal: 5 3 8
In-Order Traversal: 3 5 8
Post-Order Traversal: 3 8 5
Enter node number to be inserted <0-END>: 2
Binary Tree is...
8
5
3
2
Pre-Order Traversal: 5 3 2 8
In-Order Traversal: 2 3 5 8
Post-Order Traversal: 2 3 8 5
Enter node number to be inserted <0-END>: 9
Binary Tree is...
9
8
5
3
2
Pre-Order Traversal: 5 3 2 8 9
In-Order Traversal: 2 3 5 8 9
Post-Order Traversal: 2 3 9 8 5
Enter node number to be inserted <0-END>: 0
Tree search process...
Enter node number to be inserted <0-END>: 8
Found data in the Tree
Enter node number to be inserted <0-END>: 1
Enter node number to be inserted <0-END>: 0


## Example-complex.cpp, Page no-679¶

In [1]:
def __add__(self, c2):
temp=Complex()
temp._Complex__real=self._Complex__real+c2._Complex__real
temp._Complex__imag=self._Complex__imag+c2._Complex__imag
return temp
class Complex:
def __init__(self):
self.__real=self.__imag=0
def getdata(self):
self.__real=float(raw_input("Real part ? "))
self.__imag=float(raw_input("Imag part ? "))
def outdata(self, msg):
print "%s(%g, %g)" %(msg, self.__real, self.__imag)
c1=Complex()
c2=Complex()
c3=Complex()
print "Addition of integer complex objects..."
print "Enter Complex Number c1..."
c1.getdata()
print "Enter Complex Number c2..."
c2.getdata()
c3=c1+c2 #invoking the overloaded + operator
c3.outdata("c3 = c1 + c2: ")
c4=Complex()
c5=Complex()
c6=Complex()
print "Addition of float complex objects..."
print "Enter Complex Number c4..."
c4.getdata()
print "Enter Complex Number c5..."
c5.getdata()
c6=c4+c5 #invoking the overloaded + operator
c6.outdata("c6 = c4 + c5: ")

Addition of integer complex objects...
Enter Complex Number c1...
Real part ? 1
Imag part ? 2
Enter Complex Number c2...
Real part ? 3
Imag part ? 4
c3 = c1 + c2: (4, 6)
Enter Complex Number c4...
Real part ? 1.5
Imag part ? 2.5
Enter Complex Number c5...
Real part ? 2.4
Imag part ? 3.7
c6 = c4 + c5: (3.9, 6.2)


## Example-1, Page no-680¶

In [1]:
N=5
def Min(arr):
m=arr[0]
for i in range(N):
if arr[i]<m:
m=arr[i]
return m
a=[55,6,7,-1,8]
b=[2.3,2.1,8.4,7.5,3.0]
i_min=Min(a)
f_min=Min(b)
print "Minimum value in integer array =", i_min
print "Minimum value in float array =", f_min

Minimum value in integer array = -1
Minimum value in float array = 2.1


## Example-2, Page no-681¶

In [1]:
def add(a, b):
return a+b
i1=10
i2=20
f1=8.2
f2=9.9
c1='#'
c2='$' print i1,"+",i2, "=", add(i1, i2) print f1,"+",f2, "=", add(f1, f2) print c1,"+",c2, "= %c" %add(ord(c1),ord(c2))  10 + 20 = 30 8.2 + 9.9 = 18.1 # +$ = G