Working with lists and tuples
Date: 11/11/2020
Time: 09:30-11:30
Tuples
print(numbers[2])
#ERROR: assignment is not allowed
numbers[2] = 55
Loops: "while" and "for"
The "while" statement
while a < 10 :
print(a)
a += 1
The "for" statement
print(a)
Exercises
(check the exercises on the github repository)
1st Exercise
Let's pretend we have a list containing the titles of all the Computational Thinking lessons. The list is ordered following the established schedule. Below is the list:
a) Define a function named lab_lessons()
which takes l_schedule
as a parameter and returns the total number of "Laboratory"
lessons.
count = 0
for title in a_list:
if title == "Laboratory":
count += 1
return count
b) Define a function named all_before_lab()
which takes l_schedule
as a parameter and returns a list containing all the lessons scheduled before the first "Laboratory"
lesson.
result = []
i = 0
title = a_list[i]
while title != "Laboratory":
result.append(title)
i += 1
title = a_list[i]
return result
c) Define a function named all_before_lab_n()
which takes l_schedule
and a number n
as parameters, and returns a list containing all the lessons scheduled before the n
th laboratory lesson. (the returned list should also include the laboratory lessons)
result = []
i = 0
count_lab = 0
while count_lab < n:
title = a_list[i]
result.append(title)
if title == "Laboratory":
count_lab += 1
i += 1
return result
d) Let's pretend we have a new list representing an extended version of the l_schedule
, such that it embeds information about the date and the duration (in hours) of the each lesson. We call the new list l_schedule_extended
and each of its elements is represented as a tuple: ([DATE],[HOURS],[TITLE])
. For instance, the second lesson "Algorithms" will have the corresponding tuple: ("16/10/20",2,"Algorithms")
. Here we have the entire l_schedule_extended
:
Define a function max_lessons_hours()
which takes l_schedule_extended
and a number max_hours
as parameters, and returns a list containing only the titles of all the lessons which could be attended with a maximum number of hours = max_hours
, starting from the first lesson of the year.
result = []
tot_hours = 0
i = 0
while tot_hours < max_hours:
title = a_list[i][2]
result.append(title)
tot_hours += a_list[i][1]
i += 1
return result