|
First Summer 2008 |
We started with a simple exercise.
These are three ways to swap the contents of two integer variables:
First we indicated that a method is very much like a recipe: it hasn = 3 m = 5 print n, m temp = n n = m m = temp print n, m (n, m) = (m, n) print n, m n = n + m m = n - m n = n - m print n, m
So we discussed this code:
def fun(x):
x = x + 1
print "x inside the function:", x
x = 3
fun(5)
print "x outside the function:", x
We pointed out that this code would have the same outcome:
def fun(x):
x = x + 1
print "x inside the function:", x
x = 3
fun(x)
print "x outside the function:", x
We indicated that the process is similar to:
However not the same happens when the values are lists:n = 3 m = n m = m + 1 print n
We pointed out that the value copied in m is an address to a list in this second example.n = [3, 1, 7, 5, 2] m = n m.append(12) print n
The address is like a number. In the first example the number in n was copied in m.
Same thing happens here except this time the number is an address (to a list).
Next we decided we wanted to define a procedure to sort a list of integers in ascending order.
We didn't know how, so we settled for a lower target.
We wrote a procedure that was determining if a list was sorted or not:
def sorted(a):
for i in range(len(a)-1):
if a[i] > a[i+1]:
return False
return True
numbers = [4, 7, 3, 1, 5]
print sorted(numbers)
numbers = [1, 2, 4, 5, 9]
print sorted(numbers)
Then we remembered that we know how to swap. So we ended up designing an algorithm for which the code was to be written tomorrow:
def sorted(a):
for i in range(len(a)-1):
if a[i] > a[i+1]:
return False
return True
def sort(a):
while not sorted(a):
for i in range(len(a)-1):
if a[i] > a[i+1]:
(a[i+1], a[i]) = (a[i], a[i+1])
To test this we have:
>>> numbers = [3, 11, 7, 5, 12, 2] >>> sort(numbers) >>> numbers [2, 3, 5, 7, 11, 12] >>>