""" Idea 1 - Most like what we did in FOP Uses a list (list of lists) """ def topTenV1(filename): fin = open(filename,"r") header = fin.readline() allCities = [] for oneRow in fin: oneRow = oneRow[:-1] #we want to clean off the newline character data = oneRow.split("\t") city = data[0] population = data[1] population = int(population) #Don't forget we have to convert to an int rather than string allCities.append( [population,city] ) allCities.sort() allCities.reverse() for index in range(10): littleList = allCities[index] pop = littleList[0] city = littleList[1] print(city,pop) """ Idea 2 - Most like what I might do on paper Keeps a running total of the top 10 """ def topTenV2(filename): fin = open(filename,"r") header = fin.readline() topTen = [] #begin by adding the first ten cities to the top 10 list for index in range(10): oneRow = fin.readline() oneRow = oneRow[:-1] #we want to clean off the newline character data = oneRow.split("\t") city = data[0] population = int(data[1]) #Don't forget we have to convert to an int rather than string topTen.append( [population,city] ) topTen.sort() topTen.reverse() #for each remaining city in the file for oneRow in fin: #Notice this starts reading where we left off, not at the beginning oneRow = oneRow[:-1] #we want to clean off the newline character data = oneRow.split("\t") city = data[0] population = int(data[1]) #Get population of #10 on your top ten list numberTen = topTen[9] #remember that #9 means the 10th spot numberTenPop = numberTen[0] #Is this city bigger than the current #10? if population > numberTenPop: topTen.pop(9) #erase the last item on the top ten list topTen.append( [population,city] ) #add this new city topTen.sort() #get it in the right position topTen.reverse() #Now Print the top 10 for x in range(10): pop = topTen[x][0] city = topTen[x][1] print(city,pop)