Created
November 25, 2020 17:58
-
-
Save rrosasl/626d50b7de9689d9100f1dd5407e8492 to your computer and use it in GitHub Desktop.
Selecting winner
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
left_voters = [] | |
losers = [] | |
for r in range(1,df.shape[1]-1): | |
#Stop loop when there are already two candidates | |
if vote_rounds[r-1].nunique() == 2: | |
break | |
#Start the new voting round | |
vote_rounds[r] = vote_rounds[r-1] | |
#FInd out who are the potential losers | |
aggre = pd.DataFrame(vote_rounds[r-1].value_counts()) | |
min_vote = aggre[r-1].min() | |
potential_losers = aggre[aggre[r-1] == min_vote].index.tolist() | |
least_votes = df[potential_losers].sum().max() | |
potential_losers_df = df[potential_losers] | |
#Choose loser based on worse overall ranking (sum of ranking): | |
sum_votes = pd.DataFrame(potential_losers_df.sum()) | |
least_ranking = sum_votes[0].max() | |
loser = sum_votes[sum_votes[0] == least_ranking].index.tolist()[0] | |
print(f'Loser of round {r} is {loser}') | |
losers.append(loser) | |
#Determining who their votes go to | |
voters_non_selected = df[df[loser] == 1].index.tolist() | |
for voter in voters_non_selected: | |
left_voters.append(voter) | |
votes_to_distribute = df.iloc[list(set(left_voters)),:] | |
votes_to_distribute = votes_to_distribute.loc[:, ~votes_to_distribute.columns.isin(losers)] | |
votes_to_distribute_t = votes_to_distribute.transpose() | |
for votr in votes_to_distribute_t.columns: | |
nxt_choice = votes_to_distribute_t[votr].min() | |
vote_goes_to = votes_to_distribute_t[votes_to_distribute_t[votr] == nxt_choice].index.tolist()[0] | |
print(f'Vote goes to {vote_goes_to}') | |
# Changing their votes | |
vote_rounds.loc[votr,r] = vote_goes_to | |
print('\n') | |
col_rounds = vote_rounds.columns.tolist() | |
vote_rounds['value'] = [1 for x in range(vote_rounds.shape[0])] | |
# Selecting winner | |
final_count = pd.DataFrame(vote_rounds.iloc[:,-2:-1].value_counts()).reset_index() | |
final_count.columns = ['candidate','final_votes'] | |
winner = final_count[final_count.final_votes == final_count.final_votes.max()]['candidate'].tolist() | |
if len(winner) > 1: | |
print('There is a draw') | |
else: | |
print(f'And the final winner is... {winner[0]} !') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment