[CentralOH] The enumerate() solution: Lessons Learned: Rules of Thumb

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Sun Dec 7 19:42:33 CET 2014

On Sun, 7 Dec 2014 09:31:12 -0800, timothy spencer <smashing_good_show at hotmail.com> wrote:

> def dump(aMap):
>     for index, bucket in enumerate(aMap):
>         for i, slot in enumerate(bucket):
>            print(index, i, slot)

> I think I have figured out how to list all the desired elements 
> using enumerate(). 

Yes, you did figure it out! Congratulations!
Your new code is much much better than your earlier code. 

There is a programming rule of thumb: 

    If it seems too complicated, it probably is. 

Your old and new code demonstrate this.

> It doesn't appear that the 'if' statements that Zed uses are 
> necessary in my code. 

Some if statements are needed, some are not. 
Certainly, you don't need an if statement in your dump().
It is common to need to do nothing in a program.
Zed had an unnecessary if statement for such[1]. That was not graceful. 
The code you ended up with _is_ graceful. 
Without any extra code to handle the situation when you 
need to do nothing, your code handles it gracefully.
Your code illustrates another programming rule of thumb:

    Do nothing gracefully.

Python often makes it easy to do nothing gracefully.
Over time, you should understand more of how Python's 
design often makes it easy to do nothing gracefully.

Earlier[2], I pointed out some weaknesses in ex39_test.py.

On Tue, 25 Nov 2014 09:15:45 -0500, jep200404 at columbus.rr.com wrote:

> Most of the free on-line tutorials have weaknesses. 
> I would say that the documentation is a bit thin, 
> and his code should be refactored. You should always 
> be looking for ways that the code could be improved. 
> What other opportunities for improvement do you see? 

His list function is shown as a top level function in 
ex39_test.py. That function clobbers the builtin list 
function. That creeps me out. 

Here's another programming rule of thumb: 

    Don't stop at the first bug.

It's broader than just about actual bugs, it's also about 
ugly awkward code, even if it works. Whenever you see one 
bad thing in code, look for more, especially for similar 
kinds of badness. Programmers tend to be consistent. 
After seeing a few ugly things in someone's code, 
I usually find many more. 

> I set the number of buckets to 8, ...

That was good for debugging. It's also good for learning. 
With fewer buckets, the number of collisions increase, 
which is one of the more interesting (albeit undesirable) 
things that dictionaries deal with. That Zed had 256 
buckets is poor, especially since his code is for teaching.

[1] line 62 of ex39_test.py from
    Exercise 39: Dictionaries, Oh Lovely Dictionaries

[2] Zed's ex39

More information about the CentralOH mailing list