INF1-IP: Week 10
Lecture 18 - Repetition 2: Recursion
- Lecture slides: TBA
- Self-guided notebook (right-click → Save As... then remove the .txt part so it is saved as an .ipynb)
Learning outcomes
- Writing recursive functions with base and recursive cases
- Following calls and return values through the call stack
- Comparing recursive and iterative approaches to repetition
- Writing recursive type hints
- Recursively searching and processing data.
Key terms
Click to expand.
Recursion
Solving a problem using a function that calls itself on a smaller or simpler version of that problem. See also: iteration.
Base case
The part of a recursive function that is handled without another recursive call, usually ending the function.
Recursive case
The part of a recursive function calls itself and, where needed, combines its result with other work.
Call stack
The record of active function calls and where they will resume when later calls return.
Stack frame
The local state and return information belonging to one active function call.
Unwinding
Returning through waiting function calls, with the most recent call finishing first.
Iteration
Repeating work using a loop. See also: recursion.
Recursion depth
The number of recursive calls active at once. Python has an (adjustable) limit to this.
New syntax
Click to expand.
type NestedList = list[item | NestedList]Defines a type for a list that may contain values of type
item, lists of those values, or lists of those lists, recursively.RecursionErrorThe exception raised when Python's limit on nested calls is exceeded.
Further practice
- Official Python tutorial:
RecursionErrorandsys.getrecursionlimit()explain Python's limit on nested calls. - W3Schools: Recursion.
- Helsinki Python MOOC: Recursion for (most) of the content covered in this lecture and More recursion examples if you'd like a deeper dive into recursive data structures.
Lecture 19 - I/O 2: Working with time
- Lecture slides: TBA
- Self-guided notebook (right-click → Save As... then remove the .txt part so it is saved as an .ipynb)
Learning outcomes
- Representing dates and times with the
datetimemodule - Calculating durations and comparing times from different time zones
- Converting between dates and strings
- Measuring elapsed time with the
timemodule - Using
async,await, andasyncio.gather()to write asynchronous code - Reading JSON data and working with the timestamps it contains
Key terms
Click to expand.
Timestamp
A date and time recording when something happened.
Parsing
Reading text according to a format to obtain values a program can work with.
UTC
Coordinated Universal Time, a common reference for expressing times from different places.
UTC offset
How far a clock is ahead of or behind UTC at a particular moment.
Aware / naive datetime
An aware datetime has usable timezone information; a naive one does not.
Asynchronous programming
Organising work so that other operations can make progress while one operation is waiting.
Coroutine
An operation created by calling an
async deffunction, which can pause and resume while awaiting results.Event loop
The mechanism that organises asynchronous work and resumes it when awaited operations are ready.
JSON
A text format for storing and exchanging structured data, including objects, arrays, numbers, and strings.
Web API
An interface through which a program requests data or actions from a web service.
New syntax
Click to expand.
time.perf_counter()Reads a clock for measuring elapsed time by subtracting two readings.
time.sleep(seconds)Pauses the current thread of execution until the timer finishes.
asyncio.sleep(seconds)Provides a timer to await, allowing other asynchronous work to run during the wait.
async def name(...):Defines a coroutine function, which can use
await.await operationWaits for an asynchronous result, allowing other scheduled work to run if
operationpauses.await asyncio.gather(first, second)Runs operations concurrently and, on success, gets their results in argument order.
json.loads(text)/json.load(file)Reads JSON from a string or an open file into Python values.
From the datetime module
date(year, month, day)Creates a date. Use
date.today()to get the current local date.datetime(year, month, day, hour, minute)Creates a date and time. Time arguments left out default to zero.
datetime.now()/datetime.now(timezone.utc)Gets the current local date and time without timezone information, or an aware datetime in UTC.
timedelta(days=1, hours=2)Represents a duration, which can be added to or subtracted from a datetime. Multiple time units are supported.
duration.total_seconds()Get the whole duration of a timedelta in seconds, including any complete days.
datetime.fromisoformat(text)/timestamp.isoformat()Convert an ISO timestamp to a datetime and a datetime back to an ISO string.
datetime.strptime(text, format)Parse a date and time using a specified format, such as
"%d/%m/%Y %H:%M".timestamp.strftime(format)Format a date and time as a string using format codes.
timestamp.astimezone(timezone.utc)Express an aware timestamp in UTC, keeping the same moment.
Further reading
- Official Python documentation: Basic date and time types, Time access and conversions, Coroutines and tasks, and JSON.
- W3Schools: Datetime and JSON.
- Helsinki Python MOOC: Times and dates and Data processing.
Tutorial
This week's tutorial time will be used for Assignment 3.
Assessment
Assignment 3 will take place on Friday (27 November), during tutorial time.
For details on the assignment, see Assessment > Assignment 3: Objects, Algorithms, Recursion, and Data Processing on Learn.