is_pangram = lambda s: not set('abcdefghijklmnopqrstuvwxyz') - set(s.lower()) >>> is_pangram('abc') False >>> is_pangram('the quick brown fox jumps over the lazy dog') True >>> is_pangram('Does the quick brown fox jump over the lazy dog?') True >>> is_pangram('Do big jackdaws love my sphinx of quartz?') True
The test string s is a pangram, if we start with the alphabet, delete every letter found in the test string, and all letters of the alphabet are deleted.
Explanation
Using lambda is a way to create a function, so one line is equivalent to writing def like:
def is_pangram(s): return not set('abcdefghijklmnopqrstuvwxyz') - set(s.lower())
set() creates a data structure in which there can be no duplicates, and here:
- The first set is the (English) letters of the alphabet, lowercase
- The second set is the characters from the test string, also in lower case. And all the duplicates also disappeared.
Subtracting things like set(..) - set(..) returns the contents of the first set, minus the contents of the second set. set('abcde') - set('ace') == set('bd') .
In this pangram test:
- we take the characters in the test string from the alphabet
- If nothing is left, then the test line contains all the letters of the alphabet and should be pangram.
If something remains, then the test line does not contain all the letters of the alphabet, so it should not be a pangram.
any spaces, punctuation marks from the set of test strings were never in the alphabetical set, so they do not matter.
set(..) - set(..) will return an empty set or a set with content. If we insert sets into the simplest True / False values ββin Python, then containers with the contents of "True" and empty containers of "False".
So, we use not to check "is there anything left?" forcing the result to True / False, depending on whether there are any leftovers or not.
not also changes True β False, and False β True. This is useful here because (the alphabet used) is β an empty set that is False , but we want is_pangram return True in this case. Conversely, (the alphabet has some leftovers) -> a set of letters that is True , but we want is_pangram return False for this.
Then return the result True / False.
is_pangram = lambda s: not set('abcdefghijklmnopqrstuvwxyz') - set(s.lower())