I’m writing a function to choose a winner in a system based on majority. If there’s no majority, then I need to remove the choice with the least votes and keep going until there is a winner with the majority of the votes. For example,
voting({'a':12, 'b':9, 'd':4})
In this case, 'a' has 12 votes, 'b' has 9, and 'd' has 4. Since 'a' does not have a majority (12/25 votes), I need to remove 'd' from the available choices, and it will have the majority (12/21). There may be any number of choices in each “ballot”, all that matters is the number one in each.
My code is for def voting(votes):
d = {}
winning_party = ''
i = 0
for key in votes.keys():
d[key] = votes[key]
while winning_party == '':
for key, vote in d.items():
if d[key] > 0.5 * sum(d.values()):
winning_party = key
return winning_party
else:
if d[key] == min(d.values()):
del d[key]
I’ve tried making minor changes but I either get an error that the dictionary changed in size during iteration, or the function stopped working.
Can anyone help me fix the code, or tell me how I can avoid changing the dictionary while it’s in the loop? I can only really use the code above, i.e. I can’t import anything or use anything other than basic functions.
1 Answer