Friday, December 20, 2019

Python script for Nanson and Black voting

I made a handy little python script for tabulating group votes with more than two candidates using either Black’s Procedure or Nanson’s Method. Both algorithms are Condorcet compliant. The algorithms require as input a text file with the ballots and control information. Once the algorithm finds a winner (or a bunch of tied winners), it deletes them from the ballots and repeats.

For instance suppose sample.txt contains:

method Black's
require 3
ballot Mickey Donald Sonic
ballot Mickey Sonic Donald
ballot Sonic Mickey Donald

Then:

$ python3 vote.py sample.txt
Options: {'method': "Black's", 'require': 3}
Ballots: 3
Valid ballots: 3
Candidates: ['Donald', 'Mickey', 'Sonic']
Method: Black's
position 1 (Condorcet): Mickey
position 2 (Condorcet): Sonic
position 3: Donald

Black’s Procedure works as follows at each stage: see if there is a Condorcet winner; if not, look for a Borda winner (the first person on each ballot gets a (reversed) Borda score of 0 points; the second gets 1 point; and so on; persons not on a ballot get n points where there are n on the ballot; the winner is determined by the lowest sum of points; note that by default the ballots are modified at subsequent stages by deleting candidates who were already selected, which means the Borda scores change from stage to stage). Nanson’s Method deletes everyone with poorer-than-average Borda score, re-ranks, and repeats until there is a winner or a tie. This is also guaranteed to return a Condorcet winner if there is one.

The code marks winners that were Condorcet winners. That may be helpful to group deliberation as it shows that the decision is bit more robust in that case. (Though a Condorcet winner in kth place, with some non-Condorcet winners before, may not mean much if the earlier winners are dubious.)

The require line specifies how many entries a ballot must contain to be valid (by default, all ballots are valid, even ones with varying numbers of votes; any unranked candidates count as tied after the last ranked candidate). The ballot lines contain the candidates that someone voted for, in order from best to least good. Candidate names are case sensitive and cannot contain spaces. To save typing, one can also introduce abbreviations with the key entry. For instance:

method Black's
require 3
key m Mickey
key d Donald
key s Sonic
ballot m d s
ballot m s d
ballot s m d

No comments:

Post a Comment