~dricottone/fiddler-231027

ref: 6a48adeee0de7a0710b0edbf1ec61e8f929ac201 fiddler-231027/vote/vote.py -rw-r--r-- 1.5 KiB
6a48adeeDominic Ricottone Initial commit 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python

import collections
import random
import statistics

def representative_vote(candidates: int) -> int:
    """Voters select at random from all available candidates."""
    return random.randint(1, candidates)

def chamber_vote(candidates: int, representatives: int) -> int:
    """All representatives of the chamber vote. A majority wins; else the
    candidate with the fewest voters is eliminated."""
    tally = collections.Counter()

    # Run vote
    for _ in range(representatives):
        tally[representative_vote(candidates)] += 1

    # Check for majority
    plurality = tally.most_common(1)[0]
    if (representatives / 2) < plurality[1]:
        return plurality[0]

    # Eliminate candidate with fewest votes; identity does not matter here
    return 0

def run1(candidates: int, representatives: int):
    majority = 0
    rounds = 0
    viable_candidates = candidates

    while not majority:
        rounds += 1
        majority = chamber_vote(viable_candidates, representatives)
        viable_candidates -= 1
    print(f"Majority in {rounds} rounds.")

def runmany(candidates: int, representatives: int, repeat: int):
    results = []
    for _ in range(repeat):
        majority = 0
        rounds = 0
        viable_candidates = candidates

        while not majority:
            rounds += 1
            majority = chamber_vote(viable_candidates, representatives)
            viable_candidates -= 1
        results.append(rounds)

    average = statistics.mean(results)
    print(f"Majority in {average} rounds on average")