def read_ballots(fname):
with open(fname) as f:
data = f.read().splitlines()
f.close()
ballots = []
for datum in data:
ballot = datum.split(",")
ballots.append(ballot)
return ballots
bs = read_ballots("in.txt")
print(bs)
[['Red', 'Green'], ['Blue'], ['Green', 'Red', 'Blue'], ['Blue', 'Green', 'Red'], ['Green']]
def find_candidates(ballots):
candidates = []
for ballot in ballots:
for candidate in ballot:
if candidate not in candidates:
candidates.append(candidate)
return candidates
cs = find_candidates(bs)
print(cs)
['Red', 'Green', 'Blue']
def find_rank(cname,ballots):
count = 0
for ballot in ballots:
if ballot[0] == cname:
count = count + 1
return count
def find_ranks(candidates,ballots):
ranks = []
for candidate in candidates:
rank = find_rank(candidate,ballots)
ranks.append((rank,candidate))
return ranks
def find_candidates_with_least_first_place_votes(ranks):
sorted_ranks = sorted(ranks)
least_votes = sorted_ranks[0][0]
result = []
for rank in ranks:
if rank[0] == least_votes:
result.append(rank[1])
return result
print(find_rank("Blue",bs))
2
ranks = find_ranks(cs,bs)
print(ranks)
[(1, 'Red'), (2, 'Green'), (2, 'Blue')]
cs_to_eliminate = find_candidates_with_least_first_place_votes(ranks)
print(cs_to_eliminate)
['Red']
def eliminate_candidate_from_candidates(cname,candidates):
result = []
for candidate in candidates:
if candidate != cname:
result.append(candidate)
return result
print(eliminate_candidate_from_candidates("Brie",cs))
['Red', 'Green', 'Blue']
import sys
def main():
ballots = read_ballots(sys.argv[1])
candidates = find_candidates(ballots)
while True:
# find candidates to eliminate
# eliminate them
if len(candidates) == 1:
# do something
break
elif len(candidates) == 0:
# do something
break
else:
continue
main()
xs = [10,20,15,90,60]
xs.sort()
print(xs)
[10, 15, 20, 60, 90]
ys = [10,20,15,90,60]
sorted_ys = sorted(ys)
print(ys)
print(sorted_ys)
[10, 20, 15, 90, 60] [10, 15, 20, 60, 90]
first_place = [(2,"G"),(2,"B"),(2,"R")]
result = sorted(first_place)
print(result)
[(2, 'B'), (2, 'G'), (2, 'R')]
first_place = [("G",3),("B",4),("R",2)]
result = sorted(first_place)
print(result)
[('B', 4), ('G', 3), ('R', 2)]
xs = [10,30,20]
ys = xs
ys.sort()
print(xs)
print(ys)
[10, 20, 30] [10, 20, 30]