Ferdig med oppgavesett 1

This commit is contained in:
Trygve 2023-09-14 14:05:08 +02:00
parent 5f9b8b0287
commit 701cb3b0e3
2 changed files with 52 additions and 20 deletions

View File

@ -1,31 +1,30 @@
def table(data, head):
# data er en liste av lister med tre elementer
t = "{:^30}|{:^25}|{:^10}|\n".format(head[0],head[1],head[2])
# Formats the data into a nice table in a string
t = "{:^25}|{:^10}|\n".format(head[0],head[1])
t += ("-"*len(t)+"\n")
for k in data:
t += ("{:^30}|{:^25}|{:^10}|\n".format(k[0],k[1], k[2]))
for n,p in data.items():
t += ("{:^25}|{:^10}|\n".format(n, p))
return(t)
def population(l):
return l[2]
def main():
with open('norway_municipalities_2017.csv') as f:
data = []
f_iter = iter(f)
# I assume the csv file will always have a heading
head = f_iter.__next__().strip("\n").split(',')
for l in f:
# we will make a dict where the the kei is the district and the value the population
d = {}
# assume the csv file always has a header
l_iter = iter(f)
l_iter.__next__()
for l in l_iter:
# we get a list where 0 is the kommune name, 1 is what fylke it is in and 2 is the population
ll = l.strip("\n").split(',')
ll[2] = int(ll[2])
data.append(ll)
data.sort()
data.sort(key=population, reverse=True)
print(table(data, head))
name = ll[1]
if name in d.keys():
d.update({name: d.get(name) + int(ll[2])})
else:
d.update({name: int(ll[2])})
head = ["District", "Population"]
res = {key: val for key, val in sorted(d.items(), key = lambda ele: ele[1], reverse=True)}
print(table(res, head))
if __name__ == "__main__":
main()

33
uke1/5:diagram.py Normal file
View File

@ -0,0 +1,33 @@
import matplotlib.pyplot as plt
import numpy as np
def main():
with open('norway_municipalities_2017.csv') as f:
# we will make a dict where the the kei is the district and the value the population
d = {}
# assume the csv file always has a header
l_iter = iter(f)
l_iter.__next__()
for l in l_iter:
# we get a list where 0 is the kommune name, 1 is what fylke it is in and 2 is the population
ll = l.strip("\n").split(',')
name = ll[1]
if name in d.keys():
d.update({name: d.get(name) + int(ll[2])})
else:
d.update({name: int(ll[2])})
head = ["District", "Population"]
res = {key: val for key, val in sorted(d.items(), key = lambda ele: ele[1], reverse=True)}
n = len(res.keys())
x = 0.5 + np.arange(n)
y = res.values()
fig, ax = plt.subplots()
ax.bar(res.keys(), y, edgecolor="white", linewidth=0.7)
ax.set(xlabel=head[0], ylabel=head[1])
plt.xticks(rotation = 90)
plt.show()
if __name__ == "__main__":
main()