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
import doctest def eliminate_candidate(ballots, to_eliminate): ''' (list, list) -> list >>> eliminate_candidate([['NDP', 'LIBERAL'], ['GREEN', 'NDP'], ['NDP', 'BLOC']], ['NDP', 'LIBERAL']) [[], ['GREEN'], ['BLOC']] >>> eliminate_candidate([], []) [] >>> eliminate_candidate([[]], []) [[]] ''' new_list = [] # Copy ballots onto new list for item in ballots: new_list.append(item) for item in new_list: for element in item: if element in to_eliminate: item.remove(element) return new_list
My first doctest is failing, giving me this output instead:
[['LIBERAL'], ['GREEN'], ['BLOC']]
Advertisement
Answer
This is the function required. It searches through the sublists:
def eliminate_candidate(ballots, to_eliminate): return [[party for party in ballot if party not in to_eliminate] for ballot in ballots] ballots = [['NDP', 'LIBERAL'], ['GREEN', 'NDP'], ['NDP', 'BLOC']] to_eliminate = ['NDP', 'LIBERAL'] print(eliminate_candidate(ballots, to_eliminate))
Output:
[[], ['GREEN'], ['BLOC']]