Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PYTHON: Write a vote counting program that reads a vote file and print out the r

ID: 3733469 • Letter: P

Question

PYTHON:

Write a vote counting program that reads a vote file and print out the ranked list of candidates The vote file format is like this: John, jimmy, Lilly Joseph, linda Essentially each line contains votes from one voter with 1-3 candidates. Assume the vote filename is votes.txt. The output of your program should be like: john 25 Lilly 15 Linda 10 Hint: use dictionary to store the votes of each candidate. Votes- Candidate-"john" If candidate in Votes: Votes[candidate] +1 Else Votes[candidatel-1

Explanation / Answer

def open_file(): fpointer = open('votes.txt') return fpointer def main(): dictlist = [] dict_of_words = dict() fp = open_file() # loop to iterate over lines in file for line in fp: for word in line.split(): if(not dict_of_words.get(word)): dict_of_words[word] = 1 else: dict_of_words[word] += 1 for key, value in dict_of_words.items(): temp = (key.lower(), value) dictlist.append(temp) print(sorted(dictlist)) main()