First Summer 2006


Lecture Notes Sixteen: Preparation for Lab Twelve and Homework Seven.
We worked out all the problems in class. You took notes, and in lab you tested the code.

The first problem was extremely simple and well known:

def add(numbers):
     sum = 0
     for number in numbers:
         sum += number
     return sum

The second was very similar:

def count(numbers):
     cnt= 0
     for num in numbers:
          if num %2 == 0: 
               cnt += 1
     return cnt

The third one was concluding this warm-up section:

def rem(numbers, num):
     result = []
     for number in numbers:
          if number != num:
               result.append(number)
     return result

Sorting took us a long time, and it was done in two stages.

Here's the complete version, finished in lab:

def sorted(numbers):
     for i in range(len(numbers)-1):
         if numbers[i] > numbers[i+1]:
             return False
     return True
     
def check(numbers):
     for i in range(len(numbers) - 1):
         if numbers[i] > numbers[i+1]:
             temp = numbers[i]
             numbers[i] = numbers[i+1]
             numbers[i+1] = temp
             
def sortasc(numbers):
     while not sorted(numbers):
         check(numbers)
     return numbers

Here's a modification suggested by Preeti during the lab:

def check(numbers):
    done = True
    for i in range(len(numbers) - 1):
        if numbers[i] > numbers[i+1]:
            done = False
            temp = numbers[i]
            numbers[i] = numbers[i+1]
            numbers[i+1] = temp
    return done

def sortasc(numbers):
    while not check(numbers):
        print "***", numbers
    return numbers

We can discuss tomorrow if this makes it more intuitive or less intuitive.

The last problem worked out with Joe Levy and (a bit) with David Gower:

def five(numbers):
    result = []
    for elem in numbers:
        if not elem in result:
            result.append(elem)
    return result

That was the lab and now you're ready for Homework Seven.

We also discussed De Morgan's law and how:

attempts > 6 or guess == secret
was a good condition for stopping.

To keep going we need for the opposite of this to be true:

not (attempts > 6 or guess == secret)
Through De Morgan's laws we have:
not (attempts > 6) and not(guess == secret)
as the condition to continue. Which amounts to:
attempts <= 6 and guess != secret
So if you're using a while that's the condition we want to use.

We talked how intuitive this is or isn't and how we need to start with what's easiest.

Then using the tools of logical transformations we can formulate our intuition in the form needed by the program.


Last updated: May 26, 2006 by Adrian German for A201/A597