Working with lists and tuples
Tuples
Similar to lists, but their values can’t be modified
numbers = (10, 30, 50, 70)
print(numbers[2])
# TypeError: 'tuple' object does not support item assignment
numbers[2] = 55
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
empty = ()
singleton = 'hello', # <-- note trailing comma
len(empty)
# 0
len(singleton)
# ('hello',)
The "for" statement
Python's for statement iterates over the items of any sequence (e.g., strings, lists, tuples), in the order that they appear in the sequence.
# What is the thickness of a sheet of paper folded 10 times?
times = [1,2,3,4,5,6,7,8,9,10]
thickness = 0.1
for i in times:
thickness *= 2
print(thickness)
# 102.4
If you do need to iterate over a sequence of numbers, the built-in function range()
comes in handy. It generates arithmetic progressions.
# What is the thickness of a sheet of paper folded 39 times?
thickness = 0.1
for i in range(39):
thickness *= 2
print(thickness)
# 54975581388.8 cm = 549755.813888 Km
# Which is more than the distance between the Earth and the Moon (384400 Km)
The given end point is never part of the generated sequence; range(10)
generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the 'step'):
list(range(5, 10))
# [5, 6, 7, 8, 9]
list(range(0, 10, 3))
# [0, 3, 6, 9]
list(range(-10, -100, -30))
# [-10, -40, -70]
The "while" statement
The while statement is used for repeated execution as long as an expression is true.
We generally use this loop when we don't know the number of times to iterate beforehand.
distance_earth_moon = 38440000000
thickness = 0.1
times = 0
while thickness < distance_earth_moon:
thickness *= 2
times += 1
print(times)
# 39
Make sure that the while loop condition becomes false at some point, otherwise, the loop will continue forever (or until the PC crashes or the laptop battery runs out)
Exercises
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:
ctp_lessons = ["Introduction to the course","Introduction to Computational Thinking","Algorithms","Laboratory","Computability","Programming languages","Organising information: ordered structures","Laboratory","Brute-force algorithms","Laboratory","Organising information: unordered structures","Laboratory","Recursion","Laboratory","Divide and conquer algorithms","Laboratory","Dynamic programming algorithms","Organising information: trees","Backtracking algorithms","Organising information: graphs","Greedy algorithms"]
1.a) Define a function named lab_lessons()
which takes ctp_lessons
as a parameter and returns the total number of "Laboratory"
lessons.
def lab_lessons(a_list):
count = 0
for title in a_list:
if title == "Laboratory":
count += 1
return count
1.b) Define a function named all_before_lab()
which takes ctp_lessons
as a parameter and returns a list containing all the lessons scheduled before the first "Laboratory"
lesson.
def all_before_lab(a_list):
result = []
i = 0
title = a_list[i]
while title != "Laboratory":
result.append(title)
i += 1
title = a_list[i]
return result
1.c) Let's pretend we have a new list representing an extended version of the ctp_lessons
, such that it embeds information about the date, time and the duration (in hours) of the each lesson. We call the new list ctp_lessons_extended
. Each element is represented as a tuple: ([HOURS],[DATE],[TIME],[TITLE])
. For instance, the third lesson "Algorithms" will have the corresponding tuple: (2,"15/10/21","12:30-14:30","Algorithms")
. Here we have the entire ctp_lessons_extended
:
ctp_lessons_extended = [(2,"12/10/22","09:30-11:30","Introduction to the course"),(2,"14/10/22","12:30-14:30 ","Introduction to Computational Thinking"),(2,"17/10/22","09:30-11:30","Algorithms"),(2,"19/10/22","09:30-11:30","Laboratory"),(2,"21/10/22","12:30-14:30","Computability"),(2,"24/10/22","09:30-11:30","Programming languages"),(2,"26/10/22","09:30-11:30","Laboratory"),(2,"28/10/22","12:30-14:30","Organising information: ordered structures"),(2,"09/11/22","09:30-11:30","Brute-force algorithms"),(2,"11/11/22","12:30-14:30","Laboratory"),(2,"14/11/22","09:30-11:30","Organising information: unordered structures"),(2,"16/11/22","09:30-11:30","Laboratory"),(2,"21/11/22","09:30-11:30","Recursion"),(2,"23/11/22","09:30-11:30","Divide and conquer algorithms"),(2,"28/11/22","09:30-11:30","Laboratory"),(2,"30/11/22","09:30-11:30","Dynamic programming algorithms"),(2,"05/12/22","09:30-11:30","Laboratory"),(2,"12/12/22","09:30-11:30","Organising information: trees"),(2,"14/12/22","09:30-11:30","Backtracking algorithms"),(2,"19/12/22","09:30-11:30","Organising information: graphs"),(2,"21/12/22","09:30-11:30","Greedy algorithms")]
Define a function max_lessons_hours()
which takes ctp_lessons_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.
def max_lessons_hours(a_list, max_hours):
result = []
tot_hours = 0
i = 0
while tot_hours < max_hours:
title = a_list[i][3]
result.append(title)
tot_hours += a_list[i][0]
i += 1
return result
1.d) One of the students attending the course, Tim Berners Lee, thinks he knows enough about the materials taught in the course, so he will take a break and go on a vacation on 11/11/22 for two weeks. Right after that, when he returns, he will attend the lectures again, starting from the first available one according to the schedule until the end of the course. Write down a portion of the code that prints the titles of the lectures that Tim Berners Lee will attend at the end of the course.
Hint: take a look at the datetime
library
from datetime import datetime
vacation_date = datetime.strptime("11/11/22", '%d/%m/%y')
back_date = vacation_date + datetime.timedelta(weeks=2)
result = []
i = 0
for lesson_tuple in ctp_lessons_extended:
lesson_date = datetime.datetime.strptime(lesson_tuple[1], '%d/%m/%y')
if lesson_date < vacation_date or lesson_date > back_date:
result.append(lesson_tuple[3])
print(result)