1

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']] 

3 Answers 3

2

Using sets becomes pretty easy!

ballots = [['NDP', 'LIBERAL'], ['GREEN', 'NDP'], ['NDP', 'BLOC']] to_eliminate = ['NDP', 'LIBERAL'] result = [list(set(x) - set(to_eliminate)) for x in ballots] result [[], ['GREEN'], ['BLOC']] 

Or:

result = [list(set(x).difference(to_eliminate)) for x in ballots] result [[], ['GREEN'], ['BLOC']] 
Sign up to request clarification or add additional context in comments.

Comments

1

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']] 

Comments

1
ballots = [['NDP', 'LIBERAL'], ['GREEN', 'NDP'], ['NDP', 'BLOC']] to_eliminate = ['NDP', 'LIBERAL'] res = [[element for element in b if element not in to_eliminate] for b in ballots] print(res) 

prints

[[], ['GREEN'], ['BLOC']] 

3 Comments

Don't use list as the name of a variable!
Your output seems to be different to the requirement stated by the OP.
But that his output is not as the stated requirement.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.