I’m new to programming and python is the first language I’ve learned.
The question I want to ask is how do you count the frequency of items in a list
so they add up in order with “PARTY_INDICES”? in my case that is.
This is a docstring for what I need to do:
''' (list of str) -> tuple of (str, list of int)
votes is a list of single-candidate ballots for a single riding.
Based on votes, return a tuple where the first element is the name of the party
winning the seat and the second is a list with the total votes for each party in
the order specified in PARTY_INDICES.
>>> voting_plurality(['GREEN', 'GREEN', 'NDP', 'GREEN', 'CPC'])
('GREEN', [1, 3, 0, 1])
'''
Since PARTY_INDICES = [NDP_INDEX, GREEN_INDEX, LIBERAL_INDEX, CPC_INDEX]
This produces a tuple of the winning party (In this case ‘GREEN’) and the list of
frequencies, where [1, 3, 0, 1]
These are global variables, lists and dictionaries:
# The indices where each party's data appears in a 4-element list.
NDP_INDEX = 0
GREEN_INDEX = 1
LIBERAL_INDEX = 2
CPC_INDEX = 3
# A list of the indices where each party's data appears in a 4-element list.
PARTY_INDICES = [NDP_INDEX, GREEN_INDEX, LIBERAL_INDEX, CPC_INDEX]
# A dict where each key is a party name and each value is that party's index.
NAME_TO_INDEX = {
'NDP': NDP_INDEX,
'GREEN': GREEN_INDEX,
'LIBERAL': LIBERAL_INDEX,
'CPC': CPC_INDEX
}
# A dict where each key is a party's index and each value is that party's name.
INDEX_TO_NAME = {
NDP_INDEX: 'NDP',
GREEN_INDEX: 'GREEN',
LIBERAL_INDEX: 'LIBERAL',
CPC_INDEX: 'CPC'
}
This is my work:
def voting_plurality(votes):
my_list = []
my_dct = {}
counter = 0
for ballot in votes:
if (ballot in my_dct):
my_dct[ballot] += 1
else:
my_dct[ballot] = 1
if (my_dct):
my_dct = my_dct.values()
new_list = list(my_dct)
return (max(set(votes), key = votes.count), new_list)
it returns:
>>> voting_plurality(['GREEN', 'GREEN', 'NDP', 'GREEN', 'CPC'])
('GREEN', [1, 1, 3])
But I want it to also include the party with no votes and is in order with PARTY_INDICES [1, 3, 0, 1]
My code may look like nonsense, but I’m really stuck and confused.
Also I cannot IMPORT anything.
There are two main problems you have. The first is that you have to capture the zero, but since there are no votes for the “liberal party”, the zero will not be reflected.
Tip Maybe you want to initialize your dictionary?
The second problem is that you are calling dict.values() which will not be in any sort of order. You need to use the dictionary, and the
PARTY_INDICESto create the correctly ordered list of numbers.Tip Maybe you can reference the keys in the dictionary and their respective positions in the
PARTY_INDICIESlistSee if you can come up with something given these tips, and update your question. If you can’t, I’m sure someone will post a full answer eventually.
Seeing as it has been 4 hours – here is a solution: