[Courses] [python] Lesson 3: Fun with Strings and Lists
Akkana Peck
akkana at shallowsky.com
Thu Jul 14 19:53:35 UTC 2011
Darrin Goodman writes:
> Sorry that it's taken me so long to reply -- been really busy. Here's my
> Lesson 3 solution for the histogram:
>
> vals = [ 0, 2, 4, 8, 16, 18, 17, 14, 9, 7, 4, 2, 1 ]
> for n in vals :
> for v in range(0, n+1) :
> if v == n :
> print " "
> else :
> print "*",
>
> After completing the exercise, I took a look to see how others had
> accomplished this but I did not really notice anyone using range(0, n+1),
> but it seems to me that this is necessary since the ending range value that
> you specify is really that value minus 1, right?
Good question! And it's good to be thinking along these lines.
A lot of programming bugs come from people *not* thinking these
things through.
In this case, though, you don't need n+1. Let's walk through the
second element in vals, which is 2. Suppose you have for v in range(0, n).
n is 2, so you're doing:
for v in range(0, 2) :
print n,
print ""
So v starts at 0 and you print an asterisk. Then v is 1 and you
print a second asterisk. Then v is 2, and we're at the end of the
range so we stop. You end up with two asterisks printed -- exactly
what you wanted.
So why does yours work too, even though your range goes to n+1?
You're going through the loop one more time than if you'd just used
n -- but on the last time though your loop over the range, you're
not printing a star that time, just a space (and a newline).
Just goes to show that there are almost always several ways to
program the same result ...
...Akkana
More information about the Courses
mailing list