Chapter 15 : File Input/Output and apmatrixes

example 15.1 page no : 162

In [1]:
'''
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()    
An exception has occurred, use %tb to see the full traceback.

SystemExit: 0
Unable to open the file named  a.txt
To exit: use 'exit', 'quit', or Ctrl-D.

example 15.2 page no : 163

In [2]:
'''
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()    
An exception has occurred, use %tb to see the full traceback.

SystemExit: 0
Unable to open the file named  a.txt
To exit: use 'exit', 'quit', or Ctrl-D.

example 15.3 page no : 167

In [3]:
'''
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
0 1
In [ ]:
 
In [ ]: