Question: Hi there, the code I found for this question is below. However, I cannot use the lambda function, so how do I solve this? Write
Hi there, the code I found for this question is below. However, I cannot use the lambda function, so how do I solve this?
Write a function called vote_calculator() that accepts a single parameter data containing a list of votes, and prints out the candidates (and the number of votes they received) in order from the most to least votes. The data that stores the votes is a list of tuples, where the first name in the tuple is the name of the voter and the second name is the candidate that they are voting for.
Unfortunately, some voters attempt to vote more than once -- if they do so, then only the first vote is counted and any other votes are ignored.
Notes:
You can assume that each candidate receives a different number of votes (i.e. there are no ties).
If a candidate does not receive any valid votes, then they are not included in the output (i.e. all candidates receive at least one vote).
You may choose to define additional functions if you wish.
For example:
| Test | Result |
|---|---|
source = [('Andrew', 'George'), ('Susan', 'Beverley'), ('Joe', 'Beverley'), ('Ewan', 'Emma'), ('Emma', 'Emma'),('Joe', 'Emma'), ('Bill', 'Beverley')] vote_calculator(source) | Beverley 3 Emma 2 George 1 |
source = [('Andrew', 'George'), ('Andrew', 'George'), ('Andrew', 'Susan')] vote_calculator(source) |
def vote_calculator(data): i=0 while i < len(data): j = i+1 while j < len(data): if data[i][0] == data[j][0]: del data[j] else: j += 1 i += 1 votes = {} for i in range(len(data)): if data[i][1] in votes: votes[data[i][1]] += 1 else: votes[data[i][1]] = 1 votes = sorted(votes.items(), key = lambda x:x[1], reverse=True) for i in range(len(votes)): if votes[i][1] != 0: print(votes[i][0],votes[i][1])
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
