0% found this document useful (0 votes)
16 views4 pages

Week 4

ucl

Uploaded by

ran ju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views4 pages

Week 4

ucl

Uploaded by

ran ju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

MATH0011 Python L3

February 9, 2024

1 MATH0011 Python L3
• Please do the Python experience survey on Moodle.
• Slides are on Moodle.
• survey is just about what programming experience you had before taking 0011. It’s really
useful for me to know that.

1.1 Python projects


• Deadline 6pm Friday 23rd February.
• Last chance to get help finding project groups is today.

2 The MATH0011 exam


• In person, closed book, written exam.
• One Python question.
• Read the Learning Outcomes file on Moodle.

2.1 Common Python misunderstanding 1


• print and return. Review 2023 Q1(b).

[ ]: def f(x):
print(x+1)
def g(x):
return x+2
f(1) # what will happen?
f(1) + g(1) # what will happen?
g(1) + g(1) # what will happen?

2.2 Common Python misunderstanding 2


• return statements immediately stop function evaluation. Review 2023 Q1(c)

[ ]: def f(a):
for i in range(100):
if a[i] > a[i+1]:
return 0

1
else:
return 1

Most common errors - print vs return (“return print(x + y)”) - returning in a loop stops the loop,
always - function execution stops when a return is encountered, no exceptions - returning too early
inside a loop - misunderstanding the memory model, = isn’t equality
There are some extremely common and fundamental misunderstandings that people make. It’s not
just exams, these are fundamental probramming errors - but exams often test them.
2023 Q1(b) - make sure you completely understand this. Run the code yourself in a notebook.
Your CoCalc account will not go away. You can always check your answers.
Even if the return is in a loop!
You should immediately recognise that code like this can’t possibly be correct. The function
returns a value when i=0, always. Other values of i are never even considered. The for loop is
pointless - something MUST be wrong. Most likely, the second for loop should appear after the
loop completed.

2.3 Using Numpy arrays as vectors


• vectorization
• how to find averages of lots of vectors - do the slow way and the fast numpy way
• randomization

[ ]: import numpy as np
x = np.array([1, 2, 3])
y = np.array([3, 2, 1])
z = np.array([2, 2, 2])
a = [x, y, z]
# want the list whose ith element is the mean of a[0][i], a[1][i], ...,
# method 1: for loops
means1 = [0 for i in range(len(a[0]))]
n = len(a)
for i in range(len(a[0])):
for j in range(len(a)):
means1[i] = means1[i] + a[j][i]/n

[ ]: # method 2: list comprehension


means2 = [sum([a[j][i] for j in range(len(a))])/n for i in range(len(a[0]))]

[ ]: # method 3: vectorization
means3 = sum(a)/len(a)
print(means1, means2, means3)

[ ]:

2
3 Debugging
• A bug is an error in your code. How do we fix them?

[ ]: for i in range(2)
print(i)

Try to read any error messages. Sometimes they’re helpful.

3.1 Print statement debugging


• Often there’s no error message but the code still doesn’t work.

[ ]: def f(x):
y = [x]
z = y.append(x + 1)
return z
f(1)

Adding print statements to your code can tell you values of variables, whether a function was
called, how far your program got before stopping, …
• print statement debugging: indicate position, var names
• Thonny debugging
• pythontutor frame diagrams

3.2 Problem solving


• Divide your problem into the smallest nontrivial parts you can.
• Code and test them separately.
“Modularize”
From Assessed Exercise 4: given an array b0 , compute the 𝑛th term of the sequence b𝑘+1 =
𝑘
1
||𝐴b𝑘 || 𝐴b𝑘 where ||x|| is defined to be √∑𝑖=1 𝑥2𝑖 .
…so write a separate function length(x) that returns ||x||.
…and test it separately.

3.3 Loop invariants


Given an array b0 , compute the 𝑛th term of the sequence b𝑘+1 = ||𝐴b𝑛 || 𝐴b𝑘 .
1

• Obviously a for loop is needed, but how do we write it?


• A loop invariant is a statement depending on the index variable that is true at the start/end
of the loop body.
• A sensible choice of loop invariant can help us write correct code.
Sometimes you end up writing loop code where you’re really not sure what is going on, or whether
what you’ve written is quite correct. Example: Assessed Exercise 4. Obviously you need a loop.

3
Should we store all the bn in a list? Could work, but it’s a bad idea. We only need one of them,
so it’s very inefficient.

3.4 Loop invariants


Given an array b0 , compute the 𝑛th term of the sequence b𝑘+1 = ||𝐴b𝑛 || 𝐴b𝑘 .
1

[ ]: def f(A, b0, n):


b = b0
for k in range(n):
# loop invariant: at the start of the loop, b is the kth term of the␣
↪sequence

b = ...
# loop invariant: at the end of the loop, b is the (k+1)st term of the␣
↪sequence

return b

If the loop invariant is true initially, and if the loop body preserves its truth, then at the end of
the loop it will still be true. So b will be b𝑛 .

3.5 Binary search example


A nonempty list l of numbers is sorted into increasing order. Write a function bs(x, l) that
returns True if x is in l and False otherwise, using binary search.
We can use loop invariants with while loops, too.

[ ]: def bs(x, l):


if x < l[0] or x >= l[-1]:
return x == l[-1]
low = 0
high = len(l) - 1
# loop invariant: l[low] <= x < l[high]
while high - low > 1:
mid = (high + low) // 2
if x >= l[mid]:
low = mid
else:
high = mid
return l[low] == x

[ ]: bs(100, [100])

You might also like