I am writing a program which reads input from a file called 'votes.txt'.
It reads in some line of information, each of which is a 'vote' with parties ordered by preference.
The program needs to take this data, and output the winner of the election.
My Code is as follows:
# Define the count_votes() function
def count_votes(to_count):
"Count each vote's preference"
output = []
for vote in to_count:
output.append(vote[0])
return output
# Define the find_lowest() function
def find_lowest(results):
"Find which party has the least votes"
to_real = []
min_ = min(results.values())
for party in results:
if results[party] == min_:
to_real.append(party)
return to_real
# Define the reallocate() function
def reallocate(results, to_real, votes):
"Reallocate votes for losing party"
for party in to_real:
for vote in votes:
if vote[0] == party:
del vote[0]
results[vote[0]] += 1
if party in results:
del results[party]
if party in vote:
del vote[vote.index(party)]
return results, votes
# Define winner() function to determine if there is an outcome
def winner(results, no_votes):
if max(results.values()) > (no_votes / 2.0):
for party in results:
if max(results.values()) == results[party]:
return party
elif max(results.values()) == (no_votes / 2.0):
output = []
for party in results:
if max(results.values()) == results[party]:
ouput.append(party)
return party
# Define the post_alloc() function
def post_alloc(results, votes):
if not winner(results, len(votes)):
lowers = find_lowest(results)
results, votes = reallocate(results, lowers, votes)
results, votes, lowers = post_alloc(results, votes)
else:
return results, votes, winner(results, len(votes))
# Define the election() function
def election():
"Calculate the result of the election"
# Take file input
input_file = []
for line in open('votes.txt', 'rU'):
input_file.append(line)
# Create list of votes
votes = []
for vote in input_file:
votes.append(vote.split())
# Create a results dictionary
results = {}
for party in votes[0]:
results[party] = 0
# Allocate first preferences
count_result = count_votes(votes)
for party in count_result:
results[party] += 1
# Continue to reallocate until there is a winner
win_list = []
results, votes, win_list = post_alloc(results, votes)
# Produce result
if type(win_list) == type(''):
print win_list, 'won the election.'
else:
print win_lit[0], win_list[1], 'tie the election.'
# Carry out program
election()
But I got this error:
>Traceback (most recent call last): > File "do_we_have_a_government.py", line 94, in > election() > File "do_we_have_a_government.py", line 85, in election > results, votes, win_list = post_alloc(results, votes) > File "do_we_have_a_government.py", line 55, in post_alloc > results, votes, lowers = post_alloc(results, votes) >TypeError: 'NoneType' object is not iterable
Thanks for any help!