Wednesday, March 16, 2016

The Most Important Programming Skill



Learn to type.

I mean REAL typing ... not hunt-and-peck-like-a-chicken typing. Typing without looking at your hands.

If you can't type, take a look at typing.com or do a Google search for "learn to type".

Why is this important? Because if you can't type, writing code will be harder ... writing documentation will be harder ... writing unit tests will be harder ... in fact, EVERYTHING will be harder.


Tuesday, March 8, 2016

Refactoring And Testing With Doctest

"If you can't test it, don't build it. If you don't test it, rip it out."
Boris Beizer

Python comes with a variety of testing frameworks which are dead simple to use. You really have no excuse not to test your code as you're writing it.

I've put together a short video where you get to look over my shoulder as I refactor the FizzBuzz program. Even though this problem is completely artificial, it still has enough complexity to make refactoring a worthwhile exercise.


Wednesday, March 2, 2016

Mini lesson: De Morgan's Laws

The any() and all() functions

You can apply the logic operators "and" and "or" to a whole series of values using Python's any() and all() functions.


Given a sequence of values S
  • all(S) returns True if every value in S is True
  • any(S) returns True if at least one value in S is True

This means
  • all(S) == (S[0] and S[1] and S[2] ...)
  • any(S) == (S[0] or S[1] or S[2] ...)

De Morgan's Laws

De Morgan's laws define the relationship between the and, or, and not operators.
  • (not A and not B and not C) == not (A or B or C)
  • (not A or not B or not C) == not (A and B and C)
By knowing these laws you can sometimes rewrite complicated logical expressions in a simpler form.

Applying De Morgan's Laws

The all() function lets you test if every value is True, but how would you test if every value is False? You could negate each value (possibly with a list comprehension)

all( [not s for s in S] )

But it's easier to apply De Morgan's law

not any(S)

Similarly, you could test for at least one False value by negating each value

any( [not s for s in S] )

But De Morgan's law allows you to rewrite this as

not all(S)


Summary

So, to summarize
  • all(S) is True when every value in S is True 
  • not any(S) is True when every value in S is False
  • any(S) is True when at least one value in S is True
  • not all(S) is True when at least one value in S is False

References

https://en.wikipedia.org/wiki/De_Morgan%27s_laws