class=nd fiddling

This commit is contained in:
Mark Pilgrim
2009-07-14 20:51:14 -04:00
parent d5af08d0cb
commit 07ced98b41
14 changed files with 121 additions and 139 deletions
+7 -7
View File
@@ -150,7 +150,7 @@ if __name__ == '__main__':
<p>The alphametics solver uses this technique to get a list of all the unique characters in the puzzle.
<pre><code class=pp>unique_characters = {c for c in ''.join(words)}</code></pre>
<pre class=nd><code class=pp>unique_characters = {c for c in ''.join(words)}</code></pre>
<p>This list is later used to assign digits to characters as the solver iterates through the possible solutions.
@@ -173,11 +173,11 @@ AssertionError</samp></pre>
<p>Therefore, this line of code:
<pre><code class=pp>assert len(unique_characters) <= 10</code></pre>
<pre class=nd><code class=pp>assert len(unique_characters) <= 10</code></pre>
<p>&hellip;is equivalent to&hellip;
<pre><code class=pp>if len(unique_characters) > 10:
<pre class=nd><code class=pp>if len(unique_characters) > 10:
raise AssertionError</code></pre>
<p>But a bit easier to read and write.
@@ -210,7 +210,7 @@ AssertionError</samp></pre>
<p>Here&#8217;s another way to accomplish the same thing, using a <a href=generators.html>generator function</a>:
<pre><code class=pp>def ord_map(a_string):
<pre class=nd><code class=pp>def ord_map(a_string):
for c in a_string:
yield ord(c)
@@ -398,7 +398,7 @@ Wesley</samp></pre>
<p id=guess>The alphametics solver uses this technique to create a dictionary that maps letters in the puzzle to digits in the solution, for each possible solution.
<pre><code class=pp>characters = tuple(ord(c) for c in sorted_characters)
<pre class=nd><code class=pp>characters = tuple(ord(c) for c in sorted_characters)
digits = tuple(ord(c) for c in '0123456789')
...
for guess in itertools.permutations(digits, len(characters)):
@@ -454,7 +454,7 @@ for guess in itertools.permutations(digits, len(characters)):
<p>This is the final piece of the puzzle (or rather, the final piece of the puzzle solver). After all that fancy string manipulation, we&#8217;re left with a string like <code>'9567 + 1085 == 10652'</code>. But that&#8217;s a string, and what good is a string? Enter <code>eval()</code>, the universal Python evaluation tool.
<pre class=screen>
<pre class='nd screen'>
<samp class=p>>>> </samp><kbd class=pp>eval('1 + 1 == 2')</kbd>
<samp class=pp>True</samp>
<samp class=p>>>> </samp><kbd class=pp>eval('1 + 1 == 3')</kbd>
@@ -464,7 +464,7 @@ for guess in itertools.permutations(digits, len(characters)):
<p>But wait, there&#8217;s more! The <code>eval()</code> function isn&#8217;t limited to boolean expressions. It can handle <em>any</em> Python expression and returns <em>any</em> datatype.
<pre class=screen>
<pre class='nd screen'>
<samp class=p>>>> </samp><kbd class=pp>eval('"A" + "B"')</kbd>
<samp class=pp>'AB'</samp>
<samp class=p>>>> </samp><kbd class=pp>eval('"MARK".translate({65: 79})')</kbd>