INF201/uke1.py
2024-09-12 08:26:47 +02:00

110 lines
3.2 KiB
Python

# Task 1
def task1():
name = input("Enter your name here:")
print(f"What's up {name}!")
# Task 2
def putinframe(text):
l = len(text)
print("-"*(l+6))
print(""+" "*(l+4) + "")
print(""+ " " + text + " "+ "")
print(""+" "*(l+4) + "")
print("-"*(l+6))
def task2():
name = input("Type your name:")
putinframe(f"Have a lovely day {name}!")
# Task 3
def square_table(c1, c2, c3):
t = "{:^10}|{:^10}|{:^10}|\n".format(c1[0],c2[0],c3[0])
t += ("-"*len(t)+"\n")
for n in range(1, len(c1)):
t += ("{:^10}|{:^10}|{:^10}|\n".format(c1[n],c2[n],c3[n]))
return(t)
def task3():
n_list = ["x"]
sq_list = [""]
cube_list = [""]
for n in range(11):
n_list.append(n)
sq_list.append(n**2)
cube_list.append(n**3)
print(square_table(n_list, sq_list, cube_list))
# task 4
def district_table(data, head):
# Formats the data into a nice table in a string
t = "{:^25}|{:^10}|\n".format(head[0],head[1])
t += ("-"*len(t)+"\n")
for n,p in data.items():
t += ("{:^25}|{:^10}|\n".format(n, p))
return(t)
def task4():
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)}
print(district_table(res, head))
# Task 5
import matplotlib.pyplot as plt
import numpy as np
def task5():
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__":
print("Task 1:")
task1()
print("\nTask 2:")
task2()
print("\nTask 3:")
task3()
print("\nTask 4:")
task4()
print("\nTask 5:")
task5()