Something went wrong. Try again.
Something went wrong. Try again.
ballot-understander script.py
1.7 kB · 61 lines
Python
at main
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162#!/usr/bin/env nix-shell#!nix-shell -i python3 -p python3
import collectionsfrom typing import Dict
ballots: list[list[int]] = []total_ballots = 0candidates: list[str] = []votes: list[list[int]] = []votes_can: list[list[str | int]] = []can_dict: Dict[str, int] = {}
for i in range(0, 24): votes.append([]) votes_can.append([])
# Expand candidates to listwith open("candidates.txt", "r") as c: for l in c.readlines(): can = l.rstrip("\n") candidates.append(can) can_dict[can] = 0
with open("ballots.txt", "r") as b: # Each line is its own ballot for bal in b.readlines(): # Get a list of all votes for that ballot, zero-indexed for easier math choices = [int(c)-1 for c in bal.split(" ")] ballots.append(choices) # Output each choice into a 1st place, 2nd place, etc array for i, c in enumerate(choices): votes[i].append(c)
with open("ballots.txt", "r") as b: total_ballots = len(b.readlines())
for v_idx, v in enumerate(votes): v_tmp = v for can_idx, can in enumerate(candidates): v_tmp = [can if x == can_idx else x for x in v_tmp] votes_can[v_idx] = v_tmp
for idx, v in enumerate(votes_can): cnt = dict(collections.Counter(v)) print(f"Place {idx+1} votes: {cnt}\n\n") # Add vote weights for can, total in cnt.items(): can_dict[can]+=(total*(idx+1))
for can, weight in can_dict.items(): wght_avg = weight/total_ballots can_dict[can] = wght_avg if len(can) < 8: padding = "\t" else: padding = "" print(f"{can}\t{padding} Average Placement: \t{str(wght_avg)[:5]}")