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

No comments:

Post a Comment