Python101/Session 2 - Data Structures/Session 2 - Exercise soluti...

265 KiB

<html> <head> </head>

Session 2 - Exercise solutions

There are often many ways to do the same thing, so these are just one way of solving the problems.

Exercise 1

In [1]:
L1 = [10, 20, 30, 40, 50, 60]
first_elem = L1[0]
last_elem = L1[-1]
print(f'First element of L1 is {first_elem} and last elements of L1 is {last_elem}')
First element of L1 is 10 and last elements of L1 is 60

Exercise 2

In [2]:
L1_sliced = L1[1:4]
print(L1_sliced)
[20, 30, 40]

Exercise 3

In [3]:
L2 = ['Hi', 'Hello', 'Hi!', 'Hey', 'Hi', 'hey', 'Hey']
L2_unique = list(set(L2))
print(L2_unique)
['Hey', 'Hello', 'Hi', 'Hi!', 'hey']

Exercise 4

In [4]:
d = {2: 122, 3: 535, 't': 'T', 'rom': 'cola'}
print(d[2])       # Print value corresponding to key 2
122
In [5]:
print(d['t'])       # Print value corresponding to key 't'
T
In [6]:
print(f"I like rom and {d['rom']}, but mostly the rom")
I like rom and cola, but mostly the rom

Exercise 5

In [7]:
n = [23, 73, 12, 84]

# By using conventional for loop
for elem in n:
    print(f'{elem} squared is {elem**2}')
23 squared is 529
73 squared is 5329
12 squared is 144
84 squared is 7056

Exercise 6

In [8]:
diameters = [10, 12, 16, 20, 25, 32]
areas = [3.1459 * dia**2 / 4 for dia in diameters]   # To use pi the math module would need to be imported
print(areas)
[78.64750000000001, 113.25240000000001, 201.3376, 314.59000000000003, 491.546875, 805.3504]
In [9]:
# Convert elements to strings and round down
print([f'{area:.0f}' for area in areas])
['79', '113', '201', '315', '492', '805']

Exercise 7

In [10]:
phonetic_alphabet = ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot']
words_of_5_chars = [word for word in phonetic_alphabet if len(word) == 5]
print(words_of_5_chars)
['Alpha', 'Bravo', 'Delta']

Exercise 8

In [11]:
s1 = {'HE170B', 'HE210B', 'HE190A', 'HE200A', 'HE210A', 'HE210A'}
s2 = {'HE200A', 'HE210A', 'HE240A', 'HE200A', 'HE210B', 'HE340A'}
s_intersection = s1.intersection(s2)
print(s_intersection)
{'HE200A', 'HE210B', 'HE210A'}

Exercise 9

In [12]:
rebar_stresses = (125, 501, 362, 156, 80, 475, 489)
fy = 435
sigma_s = [stress if stress <= 435 else fy for stress in rebar_stresses]
print(sigma_s)
[125, 435, 362, 156, 80, 435, 435]

Exercise 10

In [13]:
T1 = (-18, -27, 2, -21, -15, 5)

T2 = []
for val in T1:
    if val > 0:
        T2.append(0)
    elif 0 > val > -25:
        T2.append(val)
    else:
        T2.append(-25)

print(T2)
[-18, -25, 0, -21, -15, 0]
In [14]:
# Alternative by list comprehension with chained if's
T3 = [0 if val > 0 else val if 0 > val > -25 else -25 for val in T1]
print(T3)
[-18, -25, 0, -21, -15, 0]
In [ ]:
 
</html>