diff --git a/advanced-iterators.html b/advanced-iterators.html index 4b64023..990afb3 100755 --- a/advanced-iterators.html +++ b/advanced-iterators.html @@ -51,7 +51,7 @@ import itertools def solve(puzzle): words = re.findall('[A-Z]+', puzzle.upper()) unique_characters = set(join(words)) - assert len(unique_characters) <= 10 + assert len(unique_characters) <= 10, 'Too many letters' first_letters = {word[0] for word in words} n = len(first_letters) sorted_characters = ''.join(first_letters) + \ @@ -161,28 +161,31 @@ if __name__ == '__main__':
Like many programming languages, Python has an assert statement. Here’s how it works.
->>> assert 1 + 1 == 2 ① ->>> assert 1 + 1 == 3 ② +>>> assert 1 + 1 == 2 ① +>>> assert 1 + 1 == 3 ② Traceback (most recent call last): File "<stdin>", line 1, in+AssertionError +>>> assert 2 + 2 == 5, "Only for very large values of 2" ③ +Traceback (most recent call last): + File "-AssertionError
assert statement is followed by any valid Python expression. In this case, the expression 1 + 1 == 2 evaluates to True, so the assert statement does nothing.
False, the assert statement will raise an AssertionError.
+AssertionError is raised.
Therefore, this line of code: -
assert len(unique_characters) <= 10
+assert len(unique_characters) <= 10, 'Too many letters'
-…is equivalent to… +
…is equivalent to this:
if len(unique_characters) > 10:
- raise AssertionError
+ raise AssertionError('Too many letters')
-But a bit easier to read and write. - -
The alphametics solver uses this exact assert statement to bail out early if the puzzle contains more than ten unique letters. Since each letter is assigned a unique digit, and there are only ten digits, a puzzle with more than ten unique letters is unsolvable.
+
The alphametics solver uses this exact assert statement to bail out early if the puzzle contains more than ten unique letters. Since each letter is assigned a unique digit, and there are only ten digits, a puzzle with more than ten unique letters can not possibly have a solution.
⁂ diff --git a/examples/alphametics.py b/examples/alphametics.py index 90840df..f1f4c0b 100755 --- a/examples/alphametics.py +++ b/examples/alphametics.py @@ -10,7 +10,7 @@ import itertools def solve(puzzle): words = re.findall('[A-Z]+', puzzle.upper()) unique_characters = set(''.join(words)) - assert len(unique_characters) <= 10 + assert len(unique_characters) <= 10, 'Too many letters' first_letters = {word[0] for word in words} n = len(first_letters) sorted_characters = ''.join(first_letters) + \