Class representatives

Save all functions into the same file named representatives.py.

The students of a class have chosen their class representative. Votes have been stored in a list where each element is one vote: a student name. Write the following functions:

votes_cand(lvotes, lcand)

Given a list of votes, lvotes, and a list of the possible candidate names, lcand, (all students in the class), returns a dictionary (dict). In this dictionary, keys are all possible candidates and values are the number of votes that each candidate has obtained. In addition, the dictionary must have the key 'null' that will have the number of null votes as value, i.e., the votes that do not correspond to any candidate. For example:

>>> lvotes = ['Anna', 'Enric', 'Roger', 'Roger', 'Anna', 'Enric', 
...  'Enric', 'Bart Simpson', 'Josep', 'Enric', 'Anna', 'Enric', 'Pol']
>>> lcand = ['Anna', 'Arnau', 'Enric', 'Josep', 'Roger', 'Pol','Zaira']
>>> dvotes = votes_cand (lvotes, lcand)
>>> if dvotes !=  {'Anna': 3, 'Arnau':0, 'Enric': 5,
...  'Josep': 1, 'Pol': 1, 'Roger': 2, 'Zaira': 0, 'null': 1}:
...     print(dvotes)

Note

More tests are provided in test-votes_cand.txt.

quant_votes(dvotes, name)

Given a dictionary such as that obtained by function votes_cand(), and a name of a candidate (str), return a tuple with a Boolean (bool) and an integer (int). If the candidate name is in the given dictionary, the Boolean will be True and the integer will be the number of votes that this candidate has obtained; otherwise, the Boolean will be False and the integer -1.

>>> d =  {'Anna': 3, 'Arnau':0, 'Enric': 5, 'Josep': 1,
... 'Pol': 1, 'Roger': 2, 'Zaira': 0, 'nuls': 1}
>>> quant_votes(d, 'Enric')
(True, 5)
>>> quant_votes(d, 'Pau')
(False, -1)

Note

More tests are provided in test-quant_votes.txt.

percent_null(dvotes)

Given a dictionary such as that obtained by function votes_cand(), return the percentage of null votes with respect to the total votes (float). Suppose that there is at least one vote in the dictionary. For example,

>>> d =  {'Anna': 3, 'Arnau':0, 'Enric': 5, 'Josep': 1,
... 'Pol': 1, 'Roger': 2, 'Zaira': 0, 'null': 1}
>>> round(percent_null(d), 2)
7.69

Note

More tests are provided in test-percent_null.txt.

win(dvotes)

Given a dictionary such as that obtained by function votes_cand(), returns a list, sorted alphabetically, with the names of the winners, i.e., those candidates who have obtained the maximum number of votes. The list will have more than one element in case of a tie. For example,

>>> d =  {'Anna': 3, 'Arnau':0, 'Enric': 5, 'Josep': 1,
...  'Pol': 1, 'Roger': 2, 'Zaira': 0, 'nuls': 1}
>>> win(d)
['Enric']
>>> d =  {'Anna': 3, 'Arnau':0, 'Enric': 5, 'Josep': 1, 'Pol': 1,
...  'Roger': 2, 'Zaira': 0, 'nuls': 1, 'Domenica': 5}
>>> win(d)
['Domenica', 'Enric']

Note

More tests are provided in test-win.txt.

Solution

A solution is provided in the representatives.py.