Solutions for the mandatory assignments on sets and dicts
1. Model an organisation of employees, management and board of directors in 3 sets.
[22]:
bd = {'Benny', 'Hans', 'Tine', 'Mille', 'Torben', 'Troels', 'Søren'}
ma = {'Tine', 'Trunte', 'Rane'}
em = {'Niels', 'Anna', 'Tine', 'Ole', 'Trunte', 'Bent', 'Rane', 'Allan', 'Stine', 'Claus', 'James', 'Lars'}
1. who in the board of directors is not an employee?
[23]:
# difference
bd - em
[23]:
{'Benny', 'Hans', 'Mille', 'Søren', 'Torben', 'Troels'}
3. how many of the management is also member of the board?
[25]:
# intersection
len(ma & bd)
[25]:
1
6. Who is an employee, member of the management, and a member of the board?
[28]:
# Intersection
em & ma & bd
[28]:
{'Tine'}
7. Who of the employee is neither a memeber or the board or management?
[29]:
em - bd - ma
[29]:
{'Allan', 'Anna', 'Bent', 'Claus', 'James', 'Lars', 'Niels', 'Ole', 'Stine'}
read about sets here: https://realpython.com/python-sets/
2. Using a list comprehension create a list of tuples from the folowing datastructure
[32]:
alphabet = {'a': 'Alpha', 'b' : 'Beta', 'g': 'Gamma'}
[37]:
[(key,value) for key, value in alphabet.items()]
[37]:
[('a', 'Alpha'), ('b', 'Beta'), ('g', 'Gamma')]
or done through a loop:
[40]:
t = []
for key, value in alphabet.items():
t.append((key, value))
t
[40]:
[('a', 'Alpha'), ('b', 'Beta'), ('g', 'Gamma')]
3. From these 2 sets:
[42]:
s1 = {'a', 'e', 'i', 'o', 'u', 'y'}
s2 = {'a', 'e', 'i', 'o', 'u', 'y', 'æ' ,'ø', 'å'}
Of the 2 sets create a:
4. Date Decoder.
A date of the form 8-MAR-85 includes the name of the month, which must be translated to a number.
Create a dict suitable for decoding month names to numbers.
Create a function which uses string operations to split the date into 3 items using the “-” character.
Translate the month, correct the year to include all of the digits.
The function will accept a date in the “dd-MMM-yy” format and respond with a tuple of ( y , m , d ).
[52]:
month_dict = {'JAN' : 1, 'FEB':2, 'MAR':3,'APR':4, 'MAY':5,'JUN':6, 'JUL':7,'AUG':8, 'SEP':9,'OCT':10,'NOV':11,'DEC':12}
def manipulate_date(x):
x = x.split('-')
return (x[0], month_dict[x[1]], x[2])
[53]:
manipulate_date('12-APR-90')
[53]:
('12', 4, '90')