Loops Again#
Yet again? Yes, and again and again, because loops are such a fundamental algorithmic tool, and because it takes some time to fully internalize loop patterns. And isn’t it appropriate that we should have some repetition in studying loops?
Python for
loops#
Python’s for
loops are convenient, flexible, and expressive. The
cost of this flexibility is that students often get confused by
their choices. The What For section was
contributed by CS 211 learning assistant
Audra McNamee (also a talented
comics artist). It especially
reviews the difference between iterating over elements of a
list (for el in li:
) and iterating over the indexes of a list
(for i in range(len(li)):
). Mixing them up is one of the very
most common errors on CS 210 exams.
The Python list
type#
We’ve already used lists a lot, but a peek inside the Python list
type will help us understand why some list operations require just
constant time and other operations require time proportional to the
length of the list. We’ll also take a quick look at the cost of
string (str
) operations, and at dictionaries (dict
).
Exercises#
Project#
The path simplification project introduces an algorithm that is almost certainly used in every map application you’ve used, including Google maps, but also in production of paper maps. It provides practice with recursion, list indexing, and loops that access and build lists.