swcarpentry / python-novice-gapminder

Plotting and Programming in Python
http://swcarpentry.github.io/python-novice-gapminder/
Other
163 stars 428 forks source link

Improve the solution to "Initializing" (Ep. 13) #583

Closed alex-ball closed 2 years ago

alex-ball commented 2 years ago

This PR seeks to improve three aspects of the solution to the "Initializing" challenge in episode 13.

  1. The solution includes the expression == None, which is contrary to PEP8 and thus widely frowned on. This PR changes it to is None, but because no-one would expect a learner to know about this, it includes a note of explanation.
  2. I find the statement "the values list is iterated three times" rather confusing, since values is only iterated once: the inner loops iterate over exactly two values each, not the whole list. (Each member of values appears in three loops, but that is not the same thing as the entire list being iterated three times.) I have suggested alternative wording.
  3. I have performed some tests and found that the second solution is not, in fact, the most efficient, if by that we mean the quickest in general.

By way of comparison, I timed the three solutions in this PR running over a shuffled list of 100_000 integers, 1000 times each, and on my machine get these timings:

For completeness, I also tested a solution that did away with testing for None (so one loop with two-ish comparisons):

smallest, largest = values[0], values[0]
for v in values:
    if v < smallest:
        smallest = v
    elif v > largest:
        largest = v
print(smallest, largest)

and that took ~3.8s.