Date post: | 02-Jan-2016 |
Category: |
Documents |
Upload: | hubert-wilson |
View: | 214 times |
Download: | 0 times |
8For-Statements
© 2010 David A Watt, University of Glasgow
Accelerated Programming 2
Part I: Python Programming
1
8-2
For-statements (1)
Many loops involve a variable that is assigned a sequence of values:
– e.g., a variable is assigned 1, then 2, ..., then 10.
Other loops involve a variable that is assigned each element of a list (or string) in turn:
– e.g., given a list [2, 3, 5, 7, 11], a variable is assigned 2, then 3, then 5, then 7, then 11.
– e.g., given a string ‘QWERTY’, a variable is assigned ‘Q’, then ‘W’, then ‘E’, then ‘R’, then ‘T’, then ‘Y’.
Such loops can be programmed most concisely as for-statements.
8-3
For-statements (2)
A for-statement is a loop that executes code a pre-determined number of times.
A for-statement has the form:
for name in expression: body
To execute this for-statement:
1. The expression is evaluated to yield a sequence s.
2. The body is executed once for each element of s, with the values s[0], s[1], …, s[–1] successively assigned to the named variable.
A sequence is a string, list, or tuple.
8-4
Example: consecutive integers
Function to print consecutive integers together with their squares:
def print_squares (p, q):# Print each integer in the range p … q # together with its square.
for n in range(p, q+1): print n, n**2
8-5
Example: tabulation (1)
Tabulation program:
def tabulate (low, high): # Tabulate the GCD of every pair of integers in the # range low … high. print_heading(low, high) for m in range(low, high+1): print_row (m, low, high)
8-6
Example: tabulation (2)
Tabulation program (continued):
def print_heading (low, high): # Print column headings in the range low … high. print 'Table of GCDs' print '\t', for n in range(low, high+1): print n, '\t', print
def print_row (m, low, high): # Print a row of GCDs of m and integers in the # range low … high. print m, '\t', for n in range(low, high+1): print gcd(m, n), '\t',
8-7
Example: list traversal
The following function traverses a list:
def print_elements (l): # Print all values in list l, one per line. for v in l: print v
8-8
Example: sorting a list (1)
Sorting function (selection-sort):
def sort (l): # Sort the list l. for i in range(0, len(l)-1): p = find_least(l, i) if p > i: least = l[p] l[p] = l[i] l[i] = least
8-9
Example: sorting a list (2)
Auxiliary function:
def find_least (l, i): # Return the position of the least element in # the sub-list l[i:]. p = i least = l[p] for j in range(i+1, len(l)): if l[j] < least: p = j least = l[p] return p
8-10
Example: computing prime numbers (1)
Problem: Compute the set of all prime numbers in the range 2…m–1.
Idea: Start with the set {2, …, m–1}. Remove all multiple of 2 from the set, then all multiples of 3, etc.
This idea leads to Eratosthenes’ sieve algorithm.
8-11
Example: computing prime numbers (2)
Function:
def primes (m): # Return a list of all prime numbers less than m. sieve = list(range(2, m)) n = 2 while n**2 < m: if n in sieve: # Remove multiples of n from sieve … for mult in range(2*n, m, n): remove(sieve, mult) n += 1 return sieve
8-12
Example: computing prime numbers (3)
Auxiliary function:
def remove (l, v): # If v is an element of list l, remove it. for i in range(0, len(l)): if l[i] == v: del l[i] return
8-13
List comprehensions
A list comprehension is an expression that iterates over the elements of a list (or several lists).
The general form is:
[ expression for name in expression if expression ]
may be replicated as often as you need
may be omitted
In the following examples assume:
ps = [2, 3, 5, 7, 11]
ws = ['a', 'an', 'the']
8-14
List comprehensions: single list
We can iterate over a single list:
[2*p for p in ps] – constructs a list of values 2*p, where p takes each value in the list ps – yields [4, 6, 10, 14, 22]
[2*w for w in ws] – constructs a list of values 2*w, where w takes each value in the list ws – yields [‘aa’, ‘anan’, ‘thethe’]
[len(w) for w in ws] – constructs a list of values len(w), where w takes each value in the list ws – yields [1, 2, 3]
8-15
List comprehensions: multiple lists
We can iterate over two (or more) lists:
[n*p for p in ps for n in range(2,4)] – constructs a list of values n*p, where p takes each value in the list ps
and n takes each value in the list [2, 3] – yields [4, 6, 6, 9, 10, 15, 14, 21, 22, 33]
8-16
List comprehensions: filtering
We can filter the list elements:
[2*p for p in ps if 2 < p < 10] – constructs a list of values 2*p, where p takes each value in the list ps
and such that 2<p<10 yields True – yields [6, 10, 14]