Ok, so I'm trying to write a method of counting ranked ballots known as Pairwise Comparison. I should specify that I am a complete novice when it comes to writing code in every sense of the word. So far I have managed to create the ballots (thanks to another user on this site) and separate them into ranked pairs according to position. Next, I need to separate them into different lists so that the candidates in each ordered pair are together regardless of rank (this is part of how one determines how well a candidate is doing in comparison to others). Here is the code I have so far:
import itertools
import random
import collections
candidates = ['Trump', 'Cruz', 'Rubio', 'Carson', 'Fiorina']
def simul_ballots(num_voters):
ballots = []
choice = candidates[:]
for _ in range(num_voters):
random.shuffle(choice)
ballots.append(choice[:])
return ballots
n=3
ballots = simul_ballots(n)
i=0
m=0
oPairs = []
while i < n:
for a, b in itertools.combinations(ballots[i], 2):
x = (a,b)
x
ops = list(x)
oPairs.append(ops)
i += 1
oPairs
l = len(oPairs)-1
k=0
j=(k+1)
while (k < l):
print oPairs[k]
while (j < l):
#if all (x in oPairs[i] for x in oPairs[j]):
if (set(oPairs[k])==set(oPairs[j])):
print oPairs[j]
j+=1
k+=1
So far I am stuck on this last section. I can't seem to understand how to compare each of the sublists to the others (without repeats, its important to have the same amount of sublists as I began with. In this example, I am only generating 3 sets of votes for the purpose for testing purposes, so there should be three ordered pairs using the same candidates, regardless of positioning (I will need positioning later to score the candidates). Any tips or suggestions in the right direction would be greatly appreciated!
I'm really not sure what you're trying to do with your code.
Since you've imported collections
, it seems like you might know that Counter
is a good tool to tally up the results of the pairwise comparisons. I'd iterate over the pairs of candidates using:
for can1, can2 in combinations(candidates, 2):
Then, iterate over each ballot:
for ballot in ballots:
If can1
appears first in the ballot, they get a point, else can2
gets a point. This can be checked with:
if ballot.index(can1) < ballot.index(can2):
After the ballots are tallied (for just this one pair), if can1
won more ballots, they get a point, else if can2
won more ballots, they get a point, else they both get half a point.
Putting this all together might look like:
from collections import Counter
vote_counter = Counter()
for can1, can2 in combinations(candidates, 2):
count1, count2 = 0, 0
for ballot in ballots:
if ballot.index(can1) < ballot.index(can2):
count1 += 1
else:
count2 += 1
if count1 > count2:
vote_counter[can1] += 1
elif count1 < count2:
vote_counter[can2] += 1
else:
vote_counter[can1] += 0.5
vote_counter[can2] += 0.5