uke3 2024

This commit is contained in:
Trygve 2024-09-29 18:45:21 +02:00
parent 366fe4df73
commit 16ced51fa8

109
uke3.py
View File

@ -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 import re
def student_information(filename): # Task 1
with open(filename, 'r', newline='', encoding='utf-8') as f: """
lines = f.readlines() Assume that we have sentences of the form
stud=[] - Ali and Per are friends.
for line in lines: - Kari and Joe know each other.
if "#" in line: - James has known Peter since school days.
continue
d=re.findall(r"[^, :\n]+", line)
stud.append({"name":d[0], "age":d[1], "phone number":d[2]})
return stud
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 Starts with an uppercase letter from I to Z.
from pathlib import Path 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): def main():
with open(file, 'r', encoding='utf-8') as f: print('Test task 1:')
txt = f.read() text = [
# re.M gjør at ^ matcher starten av hver linje istedet for bare starten av stringen 'Ali and Per and friends.',
ptr1 = re.compile(r"^import\s(\w+)", flags=re.M) 'Kari and Joe know each other.',
ptr2 = re.compile(r"^from\s(\w+)", flags=re.M) 'James has known Peter since school days.'
imports = re.findall(ptr1, txt) ]
imports += re.findall(ptr2, txt) print(get_friends(text))
# vi filtrerer ut duplikater: print('Test task 1:')
res = [] print('Valid:')
[res.append(x) for x in imports if x not in res] print(f'J1234: {validate_password("J1234")}')
return res 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")}')
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)}')
print_imp_dir()
if __name__ == '__main__':
main()