'''
example 15.1 page no : 162
'''
try:
fileName = "a.txt"
f = open(fileName,"r")
except:
print "Unable to open the file named " , fileName;
import sys
sys.exit(0)
# reading file line by line
for i in f.readlines():
print i
f.close()
'''
example 15.2 page no : 163
'''
try:
fileName = "a.txt"
outputFile = "b.txt"
f = open(fileName,"r")
w = open(outputFile,"w")
except:
print "Unable to open the file named " , fileName;
import sys
sys.exit(0)
# reading file line by line
for i in f.readlines():
w.write(i)
print i
f.close()
w.close()
'''
example 15.3 page no : 167
'''
class Set:
def __init__(self,n):
self.elements = []
self.numElements = 0
def getNumElements(self):
return self.numElements
def getElement(self,i):
if (i < self.numElements):
return slef.elements[i];
else:
print "Set index out of range."
import sys
sys.exit(0)
def find(self,s):
for i in range(self.numElements):
if (self.elements[i] == s):
return i;
return -1;
def add(self,s):
# if the element is already in the set, return its index
index = self.find(s);
if (index != -1):
return index;
# if the apvector is full, double its size
# add the new elements and return its index
self.elements.append(s)
self.numElements += 1
return self.numElements - 1;
cities= Set (2);
city1 = 'ahmedabad'
city2 = 'rajkot'
index1 = cities.add(city1);
index2 = cities.add(city2)
print index1, index2