INF201/uke3.py

77 lines
2.3 KiB
Python
Raw Normal View History

2024-09-29 16:45:21 +00:00
import re
# Task 1
2023-09-28 12:58:25 +00:00
"""
2024-09-29 16:45:21 +00:00
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.
2023-09-28 12:58:25 +00:00
2024-09-29 16:45:21 +00:00
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
2023-09-28 12:58:25 +00:00
"""
2024-09-29 16:45:21 +00:00
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)
2023-09-28 12:58:25 +00:00
2024-09-29 16:45:21 +00:00
# Task 2
"""
Write a Python function validate_password that checks if a given password string is valid based on the following rules:
2023-09-28 12:58:25 +00:00
2024-09-29 16:45:21 +00:00
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
2023-09-28 12:58:25 +00:00
2024-09-29 16:45:21 +00:00
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")}')
2023-09-28 12:58:25 +00:00
2024-09-29 16:45:21 +00:00
if __name__ == '__main__':
main()