Lec05 Iteration
Lec05 Iteration
Lec05 Iteration
Petr Pošík
Prerequisities:
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is
something that computers do well and people do poorly.
Repeated execution of a set of statements is called iteration. Because iteration is so common, Python provides several
language features to make it easier.
Loop types
for-loops suitable when a piece of code shall be ran a number of times with a known number of repetitions, and
while-loops when the number of iterations is not known in advance.
For-loops
The general form of a for statement is as follows:
Execution:
The <variable> following for is bound to the first value in the <sequence>, and the <code block> is executed.
The <variable> is then assigned the second value in the <sequence>, and the <code block> is executed
again.
...
The process continues until the sequence is exhausted, or a break statement is executed within the code block.
For or For-each?
A good way of thinking about the for-loop is to actually read it as for each like:
1 z 11
Iterating over characters of a string
The for-loop can be easilly used to iterate over characters of a string.
Write a program that computes the sum of all digits in a given string:
As a piece of code:
In [2]: sum = 0
for char in string:
sum += int(char)
print(sum)
45
As a function:
print(sum_num(string))
45
2, 4, 6,
2, 4, 6,
The range function is a generator, i.e. it does not produce the whole sequence when called; rather, it generates the next
number of the sequence when asked. To collect all the numbers of the sequence, we need to enclose the call to range in
a list.
2 z 11
In [7]: print(list(range(10)))
start, end, step = 13, 2, -3
print(list(range(start, end, step)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[13, 10, 7, 4]
Nested for-loops
When a for-loop is inside the code block of another for-loop, we call them nested. Two nested loops can be used e.g. to
generate all pairs of values from two sequences:
1, 2, 3, 4, 5,
2, 4, 6, 8, 10,
3, 6, 9, 12, 15,
Suppose we want to print out the work days and their number. The classic way to do this would be:
Python has a function (generator) enumerate. It produces pairs of item index and the index itself:
In [12]: list(enumerate(workdays))
3 z 11
In [13]: for i, day_name in enumerate(workdays):
print('The day nr.', i, 'is', day_name)
Note that after the for command we have a pair of variables instead of the usual single variable. (This can be even
generalized and we can easily iterate over n-tuples.) We do not have to measure the length of the list, we do not have to
index into the list. This approach is more Pythonic than the previous one.
None
In [17]: s1 = ['a','b','c','d']
s2 = [1,2,3,4]
list(zip(s1, s2))
Out[17]: [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
13
4 z 11
Iterating over nested lists
Suppose you have a list of lists (or similar nested data structure), where the inner lists may be of different lengths. You
want to go over all items in the nested lists.
Li Na K F Cl Br I
Often it may be convenient to construct an infinite while-loop by starting it with while True:, and ending the cycle by
calling break when some condition is satisfied inside the loop.
in case of for-loop, the control variable is bound to the next item of the sequence,
in case of while-loop, the test is re-evaluated, and the next iteration is started.
Very often, it is convenient to use continue to filter out the iterations for which the loop should not be executed.
1,5,7,11,13,
5 z 11
In [22]: thing = "Something Posing As Meat"
for char in thing:
if not char.isupper(): continue
print(char, end='')
SPAM
Using break statement to exhaustively search for a cube root of a non-negative integer:
In [25]: cube_root(27)
Out[25]: 3
In [26]: print(cube_root(28))
None
Execution:
6 z 11
In [27]: def square_int(n):
"""Return the square of int n by n times adding n."""
ans = 0
iters_left = n
while iters_left != 0:
ans = ans + n
iters_left = iters_left - 1
return ans
In [28]: n = 10
print(n, '*', n, '=', square_int(n))
10 * 10 = 100
Let's redefine the function by allowing it to print some info during the iterations.
In [30]: n = 6
print(n, '*', n, '=', square_int(n, info=True))
Let's see how long it takes the bacteria to double their numbers for r = 0.21:
In [31]: time = 0
ini_popsize = 1000 # 1000 bacteria in the beginning
growth_rate = 0.21 # 21 % growth per minute
7 z 11
In [33]: popsize = ini_popsize
while popsize < 2 * ini_popsize:
popsize = popsize + growth_rate * popsize
time += 1
print('After', time, 'minutes, the population size is', round(popsize))
Examples
Options:
We should find a reasonably precise approximation to the square root, i.e. we should find a number which is close
enough - its square is in a distance at most epsilon from the given square.
In [36]: sqrt_exhaustive(0.25)
8 z 11
The algorithm will make about sqrt(x) / step steps.
In [37]: sqrt_exhaustive(123456)
Why didn't we find a solution? There surely is a floating point number that approximates the square root of 123456 to
within 0.01. The program did not find it because the step was too large and it jumped over the solution. Try to make step
equal to epsilon**3. It will eventually find the answer, but you might not have the patience to wait for it.
Bisection
Suppose we know that a good approximation to the square root of x lies somewhere between 0 (low) and n (high). We
exploit the fact that the numbers are ordered. We can start by guessing that the approximation lies in the middle between
low and high. If the guess is not correct, it can be either too low, so the solution must lie in the right half, or it is too high,
then the solution must be in the left half. And we can apply the same method again in a smaller interval.
In [40]: sqrt_bisection(0.0025)
Out[40]: (0.0625, 3)
9 z 11
In [42]: sqrt_bisection(123456)
It found a different approximation than the previous function. Both solutions meet the problem specifications.
It needed only 13 steps to find the answer to √25 ‾ . When you try to find √123456
‾‾ ‾‾‾‾‾‾‾, only 45 iterations are needed.
The search space is cut in half each iteration. When doing enumeration (previous case), we reduce the search
space by a small amount only each iteration.
There is nothing special about using this algorithm to find the square roots. With a small modifications you can
use it to compute cube roots. Generally, you can find a root of any function, once you find a low and high limit
bracketing the root.
Newton-Raphson
The Newton-Raphson algorithm is the most often used approximation algorithm. It can find real roots of many continuous
functions, but here we concentrate on polynomials. The problem of finding an approximation g for the square root of 24
can be formulated as finding a g such that f (g) = g2 − 24 = 0. Square root of a general number x is approximated by
finding root of f (g) = g2 − x = 0.
Newton proved a theorem that implies that if a value, call it g as guess, is an approximation to a root of f (g) , the
f (g)
g− ,
f ′ (g)
For any constant b and any coefficient a, the first derivative of ax 2 + b is 2ax. Thus, to improve our guess g of square
root of x , we can use
x
f (g) g2 − x g+ g
gnew ← g − ′
= g− = .
f (g) 2g 2
guess = 12.5
guess = 7.25
guess = 5.349137931034482
guess = 5.011394106532552
guess = 5.000012953048684
Out[45]: (5.000012953048684, 5)
10 z 11
In [46]: sqrt_NR(123456)
Notebook config
Some setup follows. Ignore it.
In [1]: %%HTML
<style>
.reveal #notebook-container { width: 90% !important; }
.CodeMirror { max-width: 100% !important; }
pre, code, .CodeMirror-code, .reveal pre, .reveal code {
font-family: "Consolas", "Source Code Pro", "Courier New", Courier, monospace;
}
pre, code, .CodeMirror-code {
font-size: inherit !important;
}
.reveal .code_cell {
font-size: 130% !important;
line-height: 130% !important;
}
</style>
11 z 11