# create votes, an empty list votes = [] # open votes.txt file votes_file = open('votes.txt', 'r') # read the next line in the file # end of file? for line in votes_file: # convert line to a list by splitting at commas vote = line.strip().split(',') # append whole vote to votes list votes.append(vote) # set result to False - there is no result yet result = False # create eliminated, an empty list, to store eliminated candidates eliminated = [] # process votes for the round while not result: # create votes_count, an empty dictionary votes_count = {} # read next item in votes list - process each vote separately # end of list? for vote in votes: # set counted to False - this vote has not been counted yet counted = False # set preference to 0 - used to iterate over vote index = 0 # until the vote is counted (i.e. a preferred candidate is found) while not counted: # is current preferenced candidate still in election? if vote[index] not in eliminated: # set vote_candidate to current candidate vote_candidate = vote[index] # is candidate already in votes_count? if vote_candidate in votes_count: # add 1 to candidate's value votes_count[vote_candidate] += 1 else: # store a new key in votes_count with candidate's name and value = 1 votes_count[vote_candidate] = 1 # set counted to True counted = True else: # check the next candidate index += 1 # get candidate with most votes from votes_count # create winner as empty string and max_votes = 0 winner = "" max_votes = 0 # check next candidate to see if highest # end of dictionary? for candidate in votes_count: # is value > max_votes? if votes_count[candidate] > max_votes: # set max_votes = value, winner = key max_votes = votes_count[candidate] winner = candidate # check to see if winner has absolute majority if max_votes > len(votes) / 2: # set result to True - a result has been determined result = True else: # get lowest ranked candidate from votes_count # create lowest as empty string and min_votes = total votes lowest = "" min_votes = len(votes) # check next candidate to see if lowest # end of dictionary? for candidate in votes_count: # is value < min_votes? if votes_count[candidate] < min_votes: # set min_votes = value, lowest = key min_votes = votes_count[candidate] lowest = candidate # append the lowest ranked candidate to the eliminated list eliminated.append(lowest) # print winner, max_votes print(winner, "wins the election with", max_votes, "votes.")