INF201/uke2.py

52 lines
1.5 KiB
Python

# Task 1
class Party:
def __init__(self, fylke, code, name, voters, votes):
self.fylke = fylke
self.code = code
self.name = name
self.voters = voters
self.votes = votes
def percent(self):
return self.votes*100/self.voters
def table_from_votes(file_path, num=None):
with open(file_path) as f:
lines = f.readlines()
f.close()
# Read all the entries into a list of parties
local_parties = []
for l in lines[1:]:
l = l.split(';')
party = Party(fylke=l[1], code=l[6], name=l[7], voters=int(l[9]), votes=int(l[12]))
local_parties.append(party)
# Combine all the local results into a list of national party results
p_codes = []
parties = []
for p in local_parties:
if p.code not in p_codes:
party = Party('Alle', p.code, p.name, p.voters, p.votes)
parties.append(party)
p_codes.append(p.code)
else:
party = next(x for x in parties if x.code == p.code)
party.voters += p.voters
party.votes += p.votes
parties.sort(key=lambda x: x.percent(), reverse=True)
# Create the table
t = '{:^25}|{:^10}|{:^10}\n'.format('Parti', 'Prosent', 'Stemmer')
t += ("-"*len(t)+"\n")
for n, p in enumerate(parties):
t += (f'{p.code:^25}|{p.percent():^10.2f}|{p.votes:^10}\n')
if n == num:
break;
return(t)
def main():
print(table_from_votes('2021-09-14_party distribution_1_st_2021.csv'))
if __name__ == '__main__':
main()