(c) Write a function with header def mostFrequentWords(wordList, frequencyList,
ID: 643914 • Letter: #
Question
(c) Write a function with header def mostFrequentWords(wordList, frequencyList, k): that takes three parameters: (i) a list of strings (words) called wordList, (ii) a list of positive integers called frequencyList, containing the frequencies of the words in wordList, and (iii) a positive integer k. You should assume that wordList and frequencyList have exactly the same length and furthermore the frequency of the word wordList[i] is given by frequencyList[i]. You may also assume that k is no larger than the length of wordList. The function should return a list consisting of the k most frequent words from wordList, with ties broken arbitrarily. The words in this list should appear in decreasing order of frequencies (again, with ties broken arbitrarily).
Explanation / Answer
inputFileName = 'gb.txt' def readfile(fname): f = open(fname, 'r') s = f.read() f.close() return s.lower() def countChars(t): charDict = {} for char in t: if char in charDict: charDict[char] += 1 else: charDict[char] = 1 return charDict def findMostCommon(charDict): mostFreq = '' mostFreqCount = 0 for k in charDict: if charDict[k] > mostFreqCount: mostFreqCount = charDict[k] mostFreq = k return mostFreq def printCounts(charDict): for k in charDict: #First, handle some chars that don't show up very well when they print if k == ' ': print ' ', charDict[k] #newline elif k == ' ': print 'space', charDict[k] elif k == ' ': print '\t', charDict[k] #tab else: print k, charDict[k] #Normal character - print it with its count def printAlphabetically(charDict): keyList = charDict.keys() keyList.sort() for k in keyList: #First, handle some chars that don't show up very well when they print if k == ' ': print ' ', charDict[k] #newline elif k == ' ': print 'space', charDict[k] elif k == ' ': print '\t', charDict[k] #tab else: print k, charDict[k] #Normal character - print it with its count def printByFreq(charDict): aList = [] for k in charDict: aList.append([charDict[k], k]) aList.sort() #Sort into ascending order aList.reverse() #Put in descending order for item in aList: #First, handle some chars that don't show up very well when they print if item[1] == ' ': print ' ', item[0] #newline elif item[1] == ' ': print 'space', item[0] elif item[1] == ' ': print '\t', item[0] #tab else: print item[1], item[0] #Normal character - print it with its count def main(): text = readfile(inputFileName) charCounts = countChars(text) mostCommon = findMostCommon(charCounts) #print mostCommon + ':', charCounts[mostCommon] #printCounts(charCounts) #printAlphabetically(charCounts) printByFreq(charCounts) main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.