# keep 3 lines around any line containing "cat", ie the line above, the line and the line below # separate one triple of lines from the next by a line with "---", and put one "---" at the top and bottom of the list # write "found 17 cats" on the last line of the destination file, where 17 is the number of lines you found containing cat # use # line with possible cat".find("cat") >= 0 # to detect a feline presence def showCatsNeighbourhood(src, dst): s, d = open(src, 'r'), open(dst, 'w') l1 = s.readline() occurs = 0 if len(l1) > 0 : d.write("---\n") l2 = s.readline() if len(l2) > 0 : l3 = s.readline() keepGoing = True while keepGoing : if l2.find("cat") >= 0 : d.write(l1) d.write(l2) d.write(l3) d.write("---\n") occurs = occurs + 1 if len(l3) > 0 : keepGoing = True else : keepGoing = False l1 = l2 l2 = l3 l3 = s.readline() d.write("found "+str(occurs)+" cats\n") s.close(); d.close() # write a class which takes a word and a synonym, and puts it in a dictionary if it is not there already, otherwise it adds it to the list of synonyms, but it doesn't store duplicates. class Thesaurus : def __init__(self) : self.dict = {} def add(self,word,synonym) : if word in self.dict : self.dict[word].add(synonym) else : self.dict[word] = set([synonym]) def lookup(self,word) : if word in self.dict : print("The synonyms of "+word+" are") idx = 1 for syn in self.dict[word] : print(" "+str(idx)+". "+syn) idx = idx + 1 else : print("There are no synonyms of "+word+".") class FamilyTree : def __init__(self,name,father,mother) : self.name = name self.father = father self.mother = mother def printTree(self,prefix) : print(prefix + self.name) if type(self.father) == type("cat") : print(prefix + "father: "+self.father) else : print(prefix + "father: ") self.father.printTree(prefix + " ") if type(self.mother) == type("cat") : print(prefix + "mother: "+self.mother) else : print(prefix + "mother: ") self.mother.printTree(prefix + " ") # create a class for Family trees which has two method functions # init which takes 3 arguments, the root person's name, either a string or a FamilyTree for the father, and the same for the mother # printTree which takes 1 argument, a prefix string for the string class FamilyTree : def __init__(self,name,father,mother) : def printTree(self,prefix) : >>> f = FamilyTree("Steve","Sam","Sarah") >>> m = FamilyTree("Norma","Norman","Nancy") >>> me = FamilyTree("Snoopy",f,m) >>> me.printTree("") Snoopy father: Steve father: Sam mother: Sarah mother: Norma father: Norman mother: Nancy >>> me.printTree("tree | ") tree | Snoopy tree | father: tree | Steve tree | father: Sam tree | mother: Sarah tree | mother: tree | Norma tree | father: Norman tree | mother: Nancy >>> me = FamilyTree("Woodstock","unknown",m) >>> me.printTree("lopsided | ") lopsided | Woodstock lopsided | father: unknown lopsided | mother: lopsided | Norma lopsided | father: Norman lopsided | mother: Nancy >>>