Given a list of ranked ballots and a list of candidates to eliminate, I need to return a new list of ranked ballots where all the candidates in the list of candidates to eliminate have been removed.
This is the code I’ve tried so far
JavaScript
x
27
27
1
import doctest
2
3
def eliminate_candidate(ballots, to_eliminate):
4
'''
5
(list, list) -> list
6
7
>>> eliminate_candidate([['NDP', 'LIBERAL'], ['GREEN', 'NDP'],
8
['NDP', 'BLOC']], ['NDP', 'LIBERAL'])
9
[[], ['GREEN'], ['BLOC']]
10
>>> eliminate_candidate([], [])
11
[]
12
>>> eliminate_candidate([[]], [])
13
[[]]
14
'''
15
new_list = []
16
17
# Copy ballots onto new list
18
for item in ballots:
19
new_list.append(item)
20
21
for item in new_list:
22
for element in item:
23
if element in to_eliminate:
24
item.remove(element)
25
26
return new_list
27
My first doctest is failing, giving me this output instead:
JavaScript
1
2
1
[['LIBERAL'], ['GREEN'], ['BLOC']]
2
Advertisement
Answer
This is the function required. It searches through the sublists:
JavaScript
1
8
1
def eliminate_candidate(ballots, to_eliminate):
2
return [[party for party in ballot if party not in to_eliminate] for ballot in ballots]
3
4
ballots = [['NDP', 'LIBERAL'], ['GREEN', 'NDP'], ['NDP', 'BLOC']]
5
to_eliminate = ['NDP', 'LIBERAL']
6
7
print(eliminate_candidate(ballots, to_eliminate))
8
Output:
JavaScript
1
2
1
[[], ['GREEN'], ['BLOC']]
2