1 of 26

Week 12

Advanced Course in Programming

30.11.2023

2 of 26

Last Week

List comprehension

Filtering items in comprehensions

Dictionary comprehensions

Recursion

3 of 26

Sorting

Problematic if we want to sort something like tuples or our own objects

E.g. tuples are by default sorted based on their first item

4 of 26

Solution: provide your own value function

5 of 26

Defining functions inside other functions

A "helper function" that is not needed elsewhere can be defined inside other function

6 of 26

Lambda-expression

Creates an anonymous function

Syntax:

lambda <parameters> : <expression>

7 of 26

For example

8 of 26

That means that…

9 of 26

Min and max

Functions min and max also have an optional key parameter

10 of 26

Function as an argument

In Python, a function can be passed as an argument:

11 of 26

Generators

Sometimes it would be useful to return values from a "series" one at a time without needing to generate the entire list

For this reason, we can use generator functions

12 of 26

For example

Generator which returns values until maximum

13 of 26

StopIteration

Generator throws a StopIteration event when there are no more values to fetch

14 of 26

Generator "comprehension"

An alternative syntax for creating a generator with a single expression

15 of 26

Functional programming

A programming paradigm where the changes in state are avoided

Lambda and expressions are examples of this

Other paradigms:

  • Imperative
  • Procedural
  • Object-oriented

16 of 26

map

Performs the given operation for all items in the sequence

17 of 26

Return value of map

map does not return a list; instead, it returns a sequence which can be iterated once

18 of 26

filter

Only selects some of the items in the original sequence based on a condition

19 of 26

reduce

Reduces the iterable sequence into a single value

20 of 26

Regular Expressions

A "language" for filtering and searching for strings

Own syntax for defining the set of accepted strings

21 of 26

In Python

22 of 26

Rules

Alternative choices can be defined with a vertical bar

23 of 26

Rules (2)

A group of accepted characters (or substrings) is given in square brackets

24 of 26

Rules (3)

Number required:

* zero or more

+ one or more

{m} exactly m

25 of 26

Other special characters

Dot denotes any character

^ means that the match must be in the beginning

$ means that the match must be in the end

26 of 26

Next Week

One more lecture.

Game programming with Pygame