Compare commits
8 Commits
fa9f0faf62
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
352173995f | ||
|
|
bb9f20981a | ||
|
|
16ced51fa8 | ||
|
|
366fe4df73 | ||
|
|
081483ed4f | ||
|
|
20bed45e10 | ||
| 82e193a278 | |||
| 9961df1c90 |
@@ -1 +0,0 @@
|
||||
,trygve,trygves-laptop,19.09.2023 21:12,file:///home/trygve/.config/libreoffice/4;
|
||||
3
MNIST/requirements.txt
Normal file
3
MNIST/requirements.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
numpy
|
||||
setuptools
|
||||
torchvision
|
||||
83
ex6.py
Normal file
83
ex6.py
Normal file
@@ -0,0 +1,83 @@
|
||||
class Person:
|
||||
def __init__(self, name: str, age: int, email: str) -> None:
|
||||
self._name: str = name
|
||||
self._age: int = age
|
||||
self._email: str = email
|
||||
|
||||
def get_details(self) -> str:
|
||||
return f"Name: {self._name}, Age: {self._age}, Email: {self._email}"
|
||||
|
||||
|
||||
class Student(Person):
|
||||
def __init__(self, name: str, age: int, email: str, student_id: int) -> None:
|
||||
super().__init__(name, age, email)
|
||||
self._student_id: int = student_id
|
||||
self._courses: list = []
|
||||
self._grades: dict[str, str] = {}
|
||||
|
||||
def enroll_in_course(self, course: 'Course') -> None:
|
||||
self._courses.append(course)
|
||||
|
||||
def assign_grade(self, course_name: str, grade: str) -> None:
|
||||
self._grades[course_name] = grade
|
||||
|
||||
def get_grades(self) -> dict[str, str]:
|
||||
return self._grades
|
||||
|
||||
|
||||
class Teacher(Person):
|
||||
def __init__(self, name: str, age: int, email: str, subject: str) -> None:
|
||||
super().__init__(name, age, email)
|
||||
self._subject: str = subject
|
||||
|
||||
def assign_grade(self, student: Student, course: 'Course', grade: str) -> None:
|
||||
student.assign_grade(course._course_name, grade)
|
||||
|
||||
class Course:
|
||||
def __init__(self, course_name: str, course_code: str) -> None:
|
||||
self._course_name: str = course_name
|
||||
self._course_code: str = course_code
|
||||
self._enrolled_students: list[Student] = []
|
||||
|
||||
def add_student(self, student: Student) -> None:
|
||||
self._enrolled_students.append(student)
|
||||
student.enroll_in_course(self)
|
||||
|
||||
def list_students(self) -> list[str]:
|
||||
return [x.get_details() for x in self._enrolled_students]
|
||||
|
||||
def main() -> None:
|
||||
thorvald = Student("Thorvald", 28, "thorvald@example.com", 456)
|
||||
johannes = Student("Johannes", 19, "Johannes@example.com", 35198)
|
||||
tora = Student("Tora", 21, "Tora@example.com", 984555)
|
||||
|
||||
ola = Teacher("Ola Normann", 56, "ola_normann@example.com", "FYS101")
|
||||
kari = Teacher("Kari Normann", 104, "kari.normann@example.com", "MATH999")
|
||||
|
||||
FYS101 = Course("Mekanikk", "FYS101")
|
||||
MATH999 = Course("Matte", "MATH999")
|
||||
|
||||
students = [thorvald, johannes, tora]
|
||||
|
||||
for student in students:
|
||||
FYS101.add_student(student)
|
||||
MATH999.add_student(student)
|
||||
|
||||
ola.assign_grade(thorvald, FYS101, "F")
|
||||
ola.assign_grade(johannes, FYS101, "E")
|
||||
ola.assign_grade(tora, FYS101, "A")
|
||||
|
||||
kari.assign_grade(thorvald, MATH999, "B")
|
||||
kari.assign_grade(johannes, MATH999, "D")
|
||||
kari.assign_grade(tora, MATH999, "A+")
|
||||
|
||||
print(f"{thorvald._name}'s grades: {thorvald.get_grades()}")
|
||||
print(f"{thorvald._name}'s grades: {johannes.get_grades()}")
|
||||
print(f"{tora._name}'s grades: {tora.get_grades()}")
|
||||
|
||||
print("Students in FYS101:")
|
||||
for student in FYS101.list_students():
|
||||
print(student)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
110
uke1.py
Normal file
110
uke1.py
Normal file
@@ -0,0 +1,110 @@
|
||||
# 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 = ["x²"]
|
||||
cube_list = ["x³"]
|
||||
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()
|
||||
@@ -1,2 +0,0 @@
|
||||
name = input("Enter your name here:")
|
||||
print(f"What's up {name}!")
|
||||
15
uke1/2:pp.py
15
uke1/2:pp.py
@@ -1,15 +0,0 @@
|
||||
def putinframe(text):
|
||||
l = len(text)
|
||||
print(l)
|
||||
print("෴"*(l+6))
|
||||
print("‖"+" "*(l+4) + "‖")
|
||||
print("‖"+ " " + text + " "+ "‖")
|
||||
print("‖"+" "*(l+4) + "‖")
|
||||
print("෴"*(l+6))
|
||||
|
||||
def main():
|
||||
name = input("Type yo name:")
|
||||
putinframe(f"What's up {name}!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,18 +0,0 @@
|
||||
def 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 main():
|
||||
n_list = ["x"]
|
||||
sq_list = ["x²"]
|
||||
cube_list = ["x³"]
|
||||
for n in range(11):
|
||||
n_list.append(n)
|
||||
sq_list.append(n**2)
|
||||
cube_list.append(n**3)
|
||||
print(table(n_list, sq_list, cube_list))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,30 +0,0 @@
|
||||
def 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 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)}
|
||||
print(table(res, head))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,33 +0,0 @@
|
||||
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()
|
||||
35
uke2.py
35
uke2.py
@@ -57,30 +57,27 @@ def table_from_votes(file_path, num=None):
|
||||
return(t)
|
||||
|
||||
# Task 2
|
||||
def get_friends(text):
|
||||
friends = []
|
||||
for s in text:
|
||||
names = re.findall(r'[A-Z]\w*', s)
|
||||
if len(names) != 2:
|
||||
raise ValueError('String does not contain excactly two capitalized words')
|
||||
friends.append(names)
|
||||
|
||||
t = '{:^20}\n'.format('Venner')
|
||||
t += ("-"*len(t)+"\n")
|
||||
for n in friends:
|
||||
t += (f'{n[0]:^10}-{n[1]:^10}\n')
|
||||
return(t)
|
||||
|
||||
def print_encoding_info(char):
|
||||
char_int = int.from_bytes(bytes(char, 'utf-8'))
|
||||
print(f"Character: '{char}'")
|
||||
if char_int < 129:
|
||||
print(f"- ASCII representation: {format(char_int, 'b')}")
|
||||
else:
|
||||
print("- Not in ASCII range")
|
||||
print(f"- UTF-8: {' '.join(format(x, 'b') for x in bytearray(char, 'utf-8'))}", end='')
|
||||
print(f' ({len(bytearray(char, "utf-8"))} bytes)')
|
||||
print('\n')
|
||||
|
||||
def print_encoding_info_list(char_list):
|
||||
for char in char_list:
|
||||
print_encoding_info(char)
|
||||
|
||||
def main():
|
||||
print(table_from_votes('2021-09-14_party distribution_1_st_2021.csv'))
|
||||
print(table_from_votes('2021-09-14_party distribution_1_st_2021.csv', 3))
|
||||
|
||||
text = [
|
||||
'Ali and Per and friends.',
|
||||
'Kari and Joe know each other.',
|
||||
'James has known Peter since school days.'
|
||||
]
|
||||
print(get_friends(text))
|
||||
print_encoding_info_list(["2", "$", "å"])
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
113
uke3.py
113
uke3.py
@@ -1,52 +1,77 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Created on Thu Sep 28 08:23:56 2023
|
||||
|
||||
@author: Inna Gumauri, Trygve Børte Nomeland
|
||||
"""
|
||||
|
||||
#%% Task 1
|
||||
|
||||
import re
|
||||
|
||||
def student_information(filename):
|
||||
with open(filename, 'r', newline='', encoding='utf-8') as f:
|
||||
lines = f.readlines()
|
||||
stud=[]
|
||||
for line in lines:
|
||||
if "#" in line:
|
||||
continue
|
||||
d=re.findall(r"[^, :\n]+", line)
|
||||
stud.append({"name":d[0], "age":d[1], "phone number":d[2]})
|
||||
return stud
|
||||
# Task 1
|
||||
"""
|
||||
Assume that we have sentences of the form
|
||||
- Ali and Per are friends.
|
||||
- Kari and Joe know each other.
|
||||
- James has known Peter since school days.
|
||||
|
||||
print(student_information("data.txt"))
|
||||
The common structure here is that each sentence contains two names and that the names are the only words beginning with capital letters. Create a regular expression that
|
||||
- matches these sentences (one sentence at a time)
|
||||
- collects the names in groups
|
||||
"""
|
||||
def get_friends(text):
|
||||
friends = []
|
||||
for s in text:
|
||||
names = re.findall(r'[A-Z]\w*', s)
|
||||
if len(names) != 2:
|
||||
raise ValueError('String does not contain excactly two capitalized words')
|
||||
friends.append(names)
|
||||
|
||||
t = '{:^20}\n'.format('Venner')
|
||||
t += ("-"*len(t)+"\n")
|
||||
for n in friends:
|
||||
t += (f'{n[0]:^10}-{n[1]:^10}\n')
|
||||
return(t)
|
||||
|
||||
|
||||
#%% Task 2
|
||||
# Task 2
|
||||
"""
|
||||
Write a Python function validate_password that checks if a given password string is valid based on the following rules:
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
Starts with an uppercase letter from I to Z.
|
||||
Contains at least one word character (a-z, A-Z, 0-9, or underscore).
|
||||
Has exactly 4 to 5 characters in length.
|
||||
Ends with a digit.
|
||||
May contain spaces between the characters but cannot start or end with a space.
|
||||
The password must end at the string's end.
|
||||
"""
|
||||
def validate_password(password):
|
||||
if re.match('[I-Z]', password) == None:
|
||||
return False
|
||||
if re.match('[a-zA-Z0-9|_]', password) == None:
|
||||
return False
|
||||
if len(password) < 4 or len(password) > 5:
|
||||
return False
|
||||
if re.search('[0-9]$', password) == None:
|
||||
return False
|
||||
# Rules 5 and 6 are already fulfilled
|
||||
return True
|
||||
|
||||
def get_imp_file(file):
|
||||
with open(file, 'r', encoding='utf-8') as f:
|
||||
txt = f.read()
|
||||
# re.M gjør at ^ matcher starten av hver linje istedet for bare starten av stringen
|
||||
ptr1 = re.compile(r"^import\s(\w+)", flags=re.M)
|
||||
ptr2 = re.compile(r"^from\s(\w+)", flags=re.M)
|
||||
imports = re.findall(ptr1, txt)
|
||||
imports += re.findall(ptr2, txt)
|
||||
|
||||
# vi filtrerer ut duplikater:
|
||||
res = []
|
||||
[res.append(x) for x in imports if x not in res]
|
||||
return res
|
||||
|
||||
def print_imp_dir(path="./"):
|
||||
p = Path(path)
|
||||
files = list(p.glob('*.py'))
|
||||
for f in files:
|
||||
print(f'{Path.cwd()}/{f}: {get_imp_file(f)}')
|
||||
def main():
|
||||
print('Test task 1:')
|
||||
text = [
|
||||
'Ali and Per and friends.',
|
||||
'Kari and Joe know each other.',
|
||||
'James has known Peter since school days.'
|
||||
]
|
||||
print(get_friends(text))
|
||||
|
||||
print('Test task 1:')
|
||||
print('Valid:')
|
||||
print(f'J1234: {validate_password("J1234")}')
|
||||
print(f'I_ab5: {validate_password("I_ab5")}')
|
||||
print(f'Z9_w4: {validate_password("Z9_w4")}')
|
||||
print('\n')
|
||||
print('Invalid:')
|
||||
print(f'A1234: {validate_password("A1234")}')
|
||||
print(f'J12345: {validate_password("J12345")}')
|
||||
print(f'I__: {validate_password("I__")}')
|
||||
print(f'?=?=)(=)/&__: {validate_password("?=?=)(=)/&")}')
|
||||
print(f' J1234: {validate_password(" J1234")}')
|
||||
|
||||
print_imp_dir()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
24
uke4.py
Normal file
24
uke4.py
Normal file
@@ -0,0 +1,24 @@
|
||||
from pathlib import Path
|
||||
|
||||
def generate_exercise_list(project_assignments_start, total_exercises):
|
||||
return [str(i) for i in range(1, project_assignments_start)] + [f'{i}{part}' for i in range(project_assignments_start, total_exercises + 1) for part in ['a', 'b']]
|
||||
|
||||
def create_directories(directory, exercises, students):
|
||||
parent_directory = Path.cwd() / directory
|
||||
|
||||
for exercise in exercises:
|
||||
exercise_path = parent_directory / Path('exercise_' + exercise)
|
||||
for student in students:
|
||||
student_path = exercise_path / student
|
||||
studentstudent_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for directory in parent_directory.glob('**/*'):
|
||||
print(directory)
|
||||
|
||||
def main():
|
||||
exercises = generate_exercise_list(5, 12)
|
||||
students = ['Ole', 'Sarah', 'Ferdinand', 'Mattis']
|
||||
create_directories('projects', exercises, students)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user