Section 9.12 Programming Phase 3: Fixing
Subsection 9.12.1 The Problem
Here’s the problem: Let’s look at the list and the index number after each iteration through the loop:
Index is 0: [10, -66, -47, 11, 505, -217]
Index is 1: [10, -47, 11, 505, -217]
Now
index
moves up to 2, and that skips over the -47. That is definitely a problem. Let’s continue...Index is 2: [10, -47, 11, 505, -217]
Index is 3: [10, -47, 11, 505, -217]
Index is 4: [10, -47, 11, 505]
But our loop goes from 0 up to and including 5, and there is no longer an element at that index, and that is where the program crashes.
That means we need to do two things:
- Advance the index only if we have a positive number at that position.
- Check the index against the length of the modified list every time through the loop.
Subsection 9.12.2 The Fix
At this point, we do not want a
for
loop, because it can’t do either of the things we need to do:- Modifying a
for
index inside the loop is considered bad programming technique. - The range of a
for
loop is calculated once, and once only.
This is really a job for a
while
loop, where we are in control of the index value, and the condition is checked every time we go through the loop. Here is the new, revised plan in pseudo-code:def remove_negative(a_list):
set index to 0.
while index < length of a_list:
if a_list[index] < 0:
delete item at the current index
else:
move forward to next index
It’s your turn. Implement the new plan and see if it does what we want.
Subsection 9.12.3 The Moral of the Story
Sometimes your first plan simply doesn’t work. The plans for your program are not engraved in stone; think of them as engraved in jello 1 .
When a program doesn’t work, don’t go right into a “change code and see if that fixes it” cycle. Instead, stop and diagnose the problem. Find out where the problem is occurring and figure out why. It’s really hard to fix a problem if you don’t know what it is.
Change the program or the plan after you know what the problem is.
Jell-O® is a registered trademark of Kraft Heinz.