CS 1

Lecture 9

Professor Devin Balkcom
devin@cs.dartmouth.edu
office: Sudikoff 211

http://www.cs.dartmouth.edu/~cs1

Reminders

  • Exam next week, 6 - 9 pm Wednesday
  • Exam review notes posted; review session Monday
  • Crib sheet permitted
  • Lab 1 due Monday

Tables and pairs

Sometimes, we want to write a program that works with pairs of things.

Example: in this part of a times table, there is an entry for each (row, column) pair.

234
5 101520
6 1218 24
7 142128
8 162432

Print the whole table

  1. Simplify the problem, solve. (First row?)
    for col in range(2, 5):
      print 5 * col,
    
  2. Generalize the solution.

    Print an arbitrary row (in PyCharm)

  3. Put the parts back together.

    Print all the rows. (in PyCharm)

Step through the times table code with the debugger.

Nested loops

  • Good for working with pairs (e.g., tables).
  • The inner loop is part of the body of the outer loop.
  • Entire inner loop runs each time through outer loop.
  • Step through carefully, writing down variable values.
  • while or for

Nested loop example

How would you draw the blocks for Arkanoid?

Selection sort

Binary search only works on a sorted list. How can we sort a list? RTFM.

But how do 'sorted()' and 'list.sort()' work?

10 volunteers will show us one way to sort.

1 professor will write the code. selection_sort.py