Week 12
Advanced Course in Programming
30.11.2023
Last Week
List comprehension
Filtering items in comprehensions
Dictionary comprehensions
Recursion
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
Solution: provide your own value function
Defining functions inside other functions
A "helper function" that is not needed elsewhere can be defined inside other function
Lambda-expression
Creates an anonymous function
Syntax:
lambda <parameters> : <expression>
For example
That means that…
Min and max
Functions min and max also have an optional key parameter
Function as an argument
In Python, a function can be passed as an argument:
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
For example
Generator which returns values until maximum
StopIteration
Generator throws a StopIteration event when there are no more values to fetch
Generator "comprehension"
An alternative syntax for creating a generator with a single expression
Functional programming
A programming paradigm where the changes in state are avoided
Lambda and expressions are examples of this
Other paradigms:
map
Performs the given operation for all items in the sequence
Return value of map
map does not return a list; instead, it returns a sequence which can be iterated once
filter
Only selects some of the items in the original sequence based on a condition
reduce
Reduces the iterable sequence into a single value
Regular Expressions
A "language" for filtering and searching for strings
Own syntax for defining the set of accepted strings
In Python
Rules
Alternative choices can be defined with a vertical bar
Rules (2)
A group of accepted characters (or substrings) is given in square brackets
Rules (3)
Number required:
* zero or more
+ one or more
{m} exactly m
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
Next Week
One more lecture.
Game programming with Pygame