-
Notifications
You must be signed in to change notification settings - Fork 0
/
lec9.tex
executable file
·545 lines (440 loc) · 13.3 KB
/
lec9.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
\documentclass{beamer}
\usepackage{listings}
\usepackage{color}
\usepackage{hyperref}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage{upquote}
% Default fixed font does not support bold face
\DeclareFixedFont{\ttb}{T1}{txtt}{bx}{n}{10} % for bold
\DeclareFixedFont{\ttm}{T1}{txtt}{m}{n}{10} % for normal
% Custom colors
\usepackage{color}
\definecolor{deepblue}{rgb}{0,0,0.5}
\definecolor{deepred}{rgb}{0.6,0,0}
\definecolor{deepgreen}{rgb}{0,0.5,0}
\usepackage{listings}
% Python style for highlighting
\newcommand\pythonstyle{\lstset{
language=Python,
basicstyle=\ttm,
otherkeywords={self}, % Add keywords here
keywordstyle=\ttb\color{deepblue},
emph={MyClass,__init__}, % Custom highlighting
emphstyle=\ttb\color{deepred}, % Custom highlighting style
stringstyle=\color{deepgreen},
frame=tb, % Any extra options here
showstringspaces=false, %
upquote=True,
columns=fullflexible,
basicstyle=\ttfamily
}}
% Python environment
\lstnewenvironment{code}[1][]
{
%\begin{small}
\pythonstyle
\lstset{#1}
%\end{small}
}
{}
\begin{document}
% Theory of functions and their correspondence to maths
% functions. Return values and None. print vs
% return. Parameters. What's the point of functions. Passing functions
% as parameters.
\begin{frame}
\frametitle{CS24420 \& MA25220 \& MT25220 \& MX35220 \& CSM0120}
\begin{center}
\begin{huge}
Lecture 9: Functions
\end{huge}
\bigskip
Amanda Clare ([email protected])
\end{center}
\end{frame}
% Guido video on type hints
\begin{frame}[fragile]
\frametitle{Functions}
\begin{itemize}
\item Maths functions vs Python functions
\item Return values, None and print
\item Named parameters
\item Passing functions as arguments
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Functions in maths}
Assume we have 2 sets, $A$ and $B$. For example: countries and capital cities
\bigskip
We could imagine all possible pairings of elements such that one
element in the pair is from $A$ and the other is from $B$.
\bigskip
For example, if
$A = \{France, UK, Spain\}$ and $B = \{Paris, London, Madrid\}$ then
the set of all possible pairs is:
\begin{multline*}
\{ (France, London), (France, Paris), (France, Madrid), \\
(UK, London),
(UK, Paris), (UK, Madrid), \\
(Spain, Paris), (Spain, London), (Spain,
Madrid) \}
\end{multline*}
\end{frame}
\begin{frame}[fragile]
\frametitle{Relations in maths}
The set of all possible pairs from $A$ and $B$ is known as the cartesian product of $A$
and $B$.
A subset of this (that is, some of the pairs but not necessarily all
of them) is called a {\em relation}.
For example:
\begin{itemize}
\item the capital cities of each country: $\{(France, Paris), (UK,
London), (Spain, Madrid) \}$
\item popular holiday destinations: $\{ (France, Paris), (UK, Paris),
(Spain, London) \}$
\item same number of letters in word: $\{ (France, London), (Spain,
Paris) \}$
\item Continental flight destinations from UK: $\{ (UK, Paris), (UK, Madrid) \}$
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Functions in maths}
\begin{itemize}
\item A {\em function} (in maths) is a relation where there's a single output for
any given input. \\
\item A single element of $B$ for every element of $A$ in the relation.
So we can pick any input element and know that an output
exists. \\
\item We also know it's the only output (there's no confusion). \\
\item We can think of a function as a mapping from elements in $A$
to elements in $B$.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Which of these are functions}
Which of these relations are functions?
\begin{itemize}
\item the capital cities of each country: $\{(France, Paris), (UK,
London), (Spain, Madrid) \}$
\item popular holiday destinations: $\{ (France, Paris), (UK, Paris),
(Spain, London) \}$
\item same number of letters in word: $\{ (France, London), (Spain,
Paris) \}$
\item Continental flight destinations from UK: $\{ (UK, Paris), (UK, Madrid) \}$
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{In Python}
\begin{code}
def capital_city(country):
capital = None
if country == "France":
capital = "Paris"
elif country == "UK":
capital = "London"
elif country == "Spain":
capital = "Madrid"
return capital
\end{code}
\end{frame}
\begin{frame}[fragile]
\frametitle{In Python}
\begin{code}
capital_dict = {
"France": "Paris",
"UK": "London",
"Spain": "Madrid"
}
def capital_city(country):
capital = None
if country in capital_dict:
capital = capital_dict[country]
return capital
\end{code}
\end{frame}
\begin{frame}[fragile]
\frametitle{Return values}
When we return a value from a function, we can collect that value into
a variable:
\begin{code}
c = capital_city("UK")
print(c)
d = capital_city("Germany")
print(d)
\end{code}
\end{frame}
\begin{frame}[fragile]
\frametitle{Functions in Python}
When talking about Python, we use the term ``function'' to refer to a block of
reusable code, defined with the \texttt{def} keyword.
Some Python functions would not satisfy the mathematical definition of
a function.
\end{frame}
\begin{frame}[fragile]
\frametitle{Return values and None}
Some functions in Python don't return a value. They are written
solely for their side effects (often printing to a screen or writing
to a file)
\begin{code}
def print_hashes(num):
for i in range(num):
print('#' * i)
\end{code}
This is still known as a {\em function} in Python, even though it seems
that it doesn't return a value. In fact it does actually return a
value: it returns the value \texttt{None}.
\bigskip
N.B. Sometimes when we write a function just for its side effects rather than
its return value we might instead choose to return a boolean,
as an indicator of success or failure.
\end{frame}
\begin{frame}[fragile]
\frametitle{Returning multiple values}
We can return a tuple of values. For example:
\begin{itemize}
\item a pair of latitude and longitude
\item the longest element in a list, and its length
\item an RGB (red-green-blue) colour triple
\end{itemize}
\begin{code}
(lat, lon) = convert_postcode("SY23 3DB")
\end{code}
\end{frame}
\begin{frame}[fragile]
\frametitle{Returning multiple values}
We can also return a dictionary of values. For example:
\begin{code}
def convert_colour(hex_colour):
red = int(hex_colour[:2], 16)
green = int(hex_colour[2:4], 16)
blue = int(hex_colour[4:], 16)
return { "r": red, "g": green, "b": blue }
rgb = convert_colour("FFA583")
print(rgb["r"])
\end{code}
\end{frame}
\begin{frame}[fragile]
\frametitle{Partial functions}
A partial function is not defined for all elements of the input set
$A$, only some
of them. For some elements there is no output.
From our previous example of two sets, which of these are partial
functions over these sets, rather than total functions?
\begin{itemize}
\item the capital cities of each country: $\{(France, Paris), (UK,
London), (Spain, Madrid) \}$
\item popular holiday destinations: $\{ (France, Paris), (UK, Paris),
(Spain, London) \}$
\item same number of letters in word: $\{ (France, London), (Spain,
Paris) \}$
\item Continental flight destinations from UK: $\{ (UK, Paris), (UK, Madrid) \}$
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Partial functions}
This matters when coding. Think about which inputs your function
should provide an answer for, and which inputs can't be handled. What
do you want to happen for other inputs?
\begin{code}
>>> import math
>>> n = math.sqrt(9)
>>> print(n)
3.0
>>> n = math.sqrt(-9)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
\end{code}
\end{frame}
\begin{frame}[fragile]
\frametitle{Parameters}
If I define a function that takes two parameters, then I must call it
with two parameters:
\begin{code}
def perimeter(width, height):
return (width*2) + (height*2)
print( perimeter(4, 5) )
\end{code}
\end{frame}
\begin{frame}[fragile]
\frametitle{Named parameters}
If we name the parameters when I supply the values then we can put
them in any order. However this is not a good idea, for code readability.
\begin{code}
def perimeter(width, height):
return (width*2) + (height*2)
print( perimeter(4, 5) )
print( perimeter(width=4, height=5) )
print( perimeter(height=5, width=4) )
\end{code}
\end{frame}
\begin{frame}[fragile]
\frametitle{Named parameters}
However we can give the parameters default values and then the names
and ability to use them in any order becomes more useful.
\begin{code}
def perimeter(width=7, height=6):
return (width*2) + (height*2)
print( perimeter(4, 5) )
print( perimeter(width=4) )
print( perimeter(height=5) )
print( perimeter() )
\end{code}
\end{frame}
\begin{frame}[fragile]
\frametitle{Functions as arguments}
We can pass functions as arguments. Here I could pass the function \texttt{len}, or
I could pass the function \texttt{first\_char}.
\begin{code}
def is_ok_text( word, f ):
score = f(word)
return score < 10
def first_char(word):
return (ord (word[0]) )
x = is_ok_text("hello", len)
y = is_ok_text("hello", first_char)
\end{code}
\end{frame}
\begin{frame}[fragile]
\frametitle{Functions as arguments}
Suppose we're playing Scrabble. We want to define rules for which
words are acceptable.
\begin{code}
def tough(word):
return ( len(word) > 3
and not word.endswith('s')
and word[0].upper() != word[0] )
def easy(word):
return True
\end{code}
Both of these functions will take a word as argument, and return a boolean.
\end{frame}
\begin{frame}[fragile]
\frametitle{Functions as arguments}
\begin{code}
def playScrabble(num_players, rules_func):
# some code to set up and play
# at some point we can test a word
word = get_word_from_player(n)
if rules_func(word):
# play carries on
else:
# choose another word
# Which rules are we playing?
playScrabble(4, tough)
\end{code}
\end{frame}
\begin{frame}[fragile]
\frametitle{Functions have a type}
Functions have the type 'function'.
\begin{code}
>>> type(perimeter)
<type 'function'>
>>> type(len)
<type 'builtin_function_or_method'>
>>> type(max)
<type 'builtin_function_or_method'>
\end{code}
When we just use the name, e.g. \texttt{perimeter} we are referring
to the function itself. When we add brackets, we are calling the
function instead, e.g. \texttt{perimeter(3,4)}.
\end{frame}
\begin{frame}[fragile]
\frametitle{Functions and types}
\begin{itemize}
\item There's no way to declare the input types or output types of
functions in Python
\item We have to do this in the documentation that we provide
instead. For example, see the documentation for numpy.loadtxt:
\url{https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html}
\item Mypy: Optional type checking for Python \url{http://mypy-lang.org/}
\item Type hints, Guido van Rossum, PyCon 2015: \url{https://www.youtube.com/watch?v=2wDvzy6Hgxg}
\end{itemize}
\begin{code}
def greeting(name: str) -> str:
return 'Hello ' + name
\end{code}
\end{frame}
% \begin{frame}[fragile]
% \frametitle{Lambda functions [Optional extra]}
% We can also define simple functions using the lambda keyword.
% \begin{code}
% number_of_ls = lambda s : return s.count('l')
% say_hello = lambda name: return "hello " + name
% print (say_hello("Amanda"))
% print (number_of_ls(say_hello("Amanda")))
% \end{code}
% \end{frame}
% \begin{frame}[fragile]
% \frametitle{Lambda functions}
% Lambda functions are a convenient notation but not necessary.
% \bigskip
% These functions are equivalent:
% \begin{code}
% number_of_ls = lambda s : s.count('l')
% def number_of_ls(s):
% return s.count('l')
% \end{code}
% \end{frame}
% \begin{frame}[fragile]
% \frametitle{Lambda functions}
% These functions are equivalent:
% \begin{code}
% say_hello = lambda name: "hello " + name
% def say_hello(name):
% return "hello " + name
% \end{code}
% \end{frame}
% \begin{frame}[fragile]
% \frametitle{Lambda functions}
% Lambda functions can only be used for simple, single line functions.
% \bigskip
% After the colon must be an expression which produces the returned
% value.
% \bigskip
% Lambda functions can take more than one argument:
% \begin{code}
% perimeter = lambda height,width : width*2 + height*2
% \end{code}
% \end{frame}
\begin{frame}
\frametitle{Why use functions}
\begin{itemize}
\item To group code into reusable units.
\item To make small, testable units of code, that are separate from
other pieces of code.
\item To structure your code so that the flow of code is readable at a high level
(details hidden by the functions).
\item Abstraction: once it's written and tested you don't need to know
how a function works inside. Just use it.
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Writing a function}
When writing a function:
\begin{itemize}
\item Decide what this function should do. Keep this simple. This is
the most difficult part.
\item Decide what parameters it should take.
\item Decide what output it should return
\item Write the code and test it.
\end{itemize}
\end{frame}
\begin{frame}[fragile]
\frametitle{Summary}
\begin{itemize}
\item Functions in maths and Python
\item Return values, None and print
\item Named parameters
\item Passing functions as arguments
\end{itemize}
\bigskip
\begin{code}
def my_function( num, modifier_func, extra=5):
x = modifier_func(num) + extra
return x
y = my_function( 4, math.sqrt, extra=8)
\end{code}
\end{frame}
\end{document}