- Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathEncodeAsString.html
291 lines (264 loc) · 30.1 KB
/
EncodeAsString.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<!DOCTYPE html>
<htmlclass="writer-html5" lang="en" >
<head>
<metacharset="utf-8" /><metacontent="Topic: String Encoding Exercise, Difficulty: Medium, Category: Practice Problem" name="description" />
<metacontent="function, string, casting, practice problem" name="keywords" />
<metaname="viewport" content="width=device-width, initial-scale=1.0" />
<title>Encode as String — Python Like You Mean It</title>
<linkrel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<linkrel="stylesheet" href="../../_static/css/theme.css" type="text/css" />
<linkrel="stylesheet" href="../../_static/my_theme.css" type="text/css" />
<!--[if lt IE 9]>
<script src="../../_static/js/html5shiv.min.js"></script>
<![endif]-->
<scriptdata-url_root="../../" id="documentation_options" src="../../_static/documentation_options.js"></script>
<scriptsrc="../../_static/jquery.js"></script>
<scriptsrc="../../_static/underscore.js"></script>
<scriptsrc="../../_static/doctools.js"></script>
<scriptasync="async" src="https://www.googletagmanager.com/gtag/js?id=UA-115029372-1"></script>
<scriptsrc="../../_static/gtag.js"></script>
<scriptcrossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script>window.MathJax={"tex": {"inlineMath": [["$","$"],["\\(","\\)"]],"processEscapes": true},"options": {"ignoreHtmlClass": "tex2jax_ignore|mathjax_ignore|document","processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script>
<scriptdefer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<scriptsrc="../../_static/js/theme.js"></script>
<linkrel="index" title="Index" href="../../genindex.html" />
<linkrel="search" title="Search" href="../../search.html" />
<linkrel="next" title="Module 3: The Essentials of NumPy" href="../../module_3.html" />
<linkrel="prev" title="Difference Fanout" href="DifferenceFanout.html" />
</head>
<bodyclass="wy-body-for-nav">
<divclass="wy-grid-for-nav">
<navdata-toggle="wy-nav-shift" class="wy-nav-side">
<divclass="wy-side-scroll">
<divclass="wy-side-nav-search" >
<ahref="../../index.html" class="icon icon-home"> Python Like You Mean It
</a>
<divclass="version">
1.4
</div>
<divrole="search">
<formid="rtd-search-form" class="wy-form" action="../../search.html" method="get">
<inputtype="text" name="q" placeholder="Search docs" />
<inputtype="hidden" name="check_keywords" value="yes" />
<inputtype="hidden" name="area" value="default" />
</form>
</div>
</div><divclass="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu">
<pclass="caption" role="heading"><spanclass="caption-text">Table of Contents:</span></p>
<ulclass="current">
<liclass="toctree-l1"><aclass="reference internal" href="../../intro.html">Python Like You Mean It</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../../module_1.html">Module 1: Getting Started with Python</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../../module_2.html">Module 2: The Essentials of Python</a></li>
<liclass="toctree-l1 current"><aclass="reference internal" href="../../module_2_problems.html">Module 2: Problems</a><ulclass="current">
<liclass="toctree-l2"><aclass="reference internal" href="MergeMaxDicts.html">Merging Two Dictionaries</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="MarginPercentage.html">Within Margin Percentage</a></li>
<liclass="toctree-l2"><aclass="reference internal" href="DifferenceFanout.html">Difference Fanout</a></li>
<liclass="toctree-l2 current"><aclass="current reference internal" href="#">Encode as String</a><ul>
<liclass="toctree-l3"><aclass="reference internal" href="#Solution">Solution</a></li>
</ul>
</li>
</ul>
</li>
<liclass="toctree-l1"><aclass="reference internal" href="../../module_3.html">Module 3: The Essentials of NumPy</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../../module_3_problems.html">Module 3: Problems</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../../module_4.html">Module 4: Object Oriented Programming</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../../module_5.html">Module 5: Odds and Ends</a></li>
<liclass="toctree-l1"><aclass="reference internal" href="../../changes.html">Changelog</a></li>
</ul>
</div>
</div>
</nav>
<sectiondata-toggle="wy-nav-shift" class="wy-nav-content-wrap"><navclass="wy-nav-top" aria-label="Mobile navigation menu" >
<idata-toggle="wy-nav-top" class="fa fa-bars"></i>
<ahref="../../index.html">Python Like You Mean It</a>
</nav>
<divclass="wy-nav-content">
<divclass="rst-content">
<divrole="navigation" aria-label="Page navigation">
<ulclass="wy-breadcrumbs">
<li><ahref="../../index.html" class="icon icon-home"></a> »</li>
<li><ahref="../../module_2_problems.html">Module 2: Problems</a> »</li>
<li>Encode as String</li>
<liclass="wy-breadcrumbs-aside">
<ahref="../../_sources/Module2_EssentialsOfPython/Problems/EncodeAsString.md.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<divrole="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<divitemprop="articleBody">
<style>
/* CSS overrides for sphinx_rtd_theme */
/* 24px margin */
.nbinput.nblast.container,
.nboutput.nblast.container {
margin-bottom:19px; /* padding has already 5px */
}
/* ... except between code cells! */
.nblast.container+ .nbinput.container {
margin-top:-19px;
}
.admonition>p:before {
margin-right:4px; /* make room for the exclamation icon */
}
/* Fix math alignment, see https://github.com/rtfd/sphinx_rtd_theme/pull/686 */
.math {
text-align: unset;
}
</style>
<divclass="section" id="Encode-as-String">
<h1>Encode as String<aclass="headerlink" href="#Encode-as-String" title="Permalink to this headline"></a></h1>
<p>Sometimes it is very important to handle different input object types differently in a function. This problem will exercise your understanding of types, control-flow, dictionaries, and more.</p>
<blockquote>
<div><p>We want to encode a sequence of Python objects as a single string. The following describes the encoding method that we want to use for each type of object. Each object’s transcription in should be separated by <codeclass="docutils literal notranslate"><spanclass="pre">"</span><spanclass="pre">|</span><spanclass="pre">"</span></code>, and the result should be one large string.</p>
</div></blockquote>
<ulclass="simple">
<li><p>If the object is an integer, convert it into a string by spelling out each digit in base-10 in this format: <codeclass="docutils literal notranslate"><spanclass="pre">142</span></code><spanclass="math notranslate nohighlight">\(\rightarrow\)</span><codeclass="docutils literal notranslate"><spanclass="pre">one-four-two</span></code>; <codeclass="docutils literal notranslate"><spanclass="pre">-12</span></code><spanclass="math notranslate nohighlight">\(\rightarrow\)</span><codeclass="docutils literal notranslate"><spanclass="pre">neg-one-two</span></code>.</p></li>
<li><p>If the object is a float, just append its integer part (obtained by rounding down) the same way and the string <codeclass="docutils literal notranslate"><spanclass="pre">"and</span><spanclass="pre">float"</span></code>: <codeclass="docutils literal notranslate"><spanclass="pre">12.324</span></code><spanclass="math notranslate nohighlight">\(\rightarrow\)</span><codeclass="docutils literal notranslate"><spanclass="pre">one-two</span><spanclass="pre">and</span><spanclass="pre">float</span></code>.</p></li>
<li><p>If the object is a string, keep it as is.</p></li>
<li><p>If the object is of any other type, return <codeclass="docutils literal notranslate"><spanclass="pre">'<OTHER>'</span></code>.</p></li>
</ul>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># example behavior</span>
<spanclass="o">>>></span><spanclass="n">s</span><spanclass="o">=</span><spanclass="n">concat_to_str</span><spanclass="p">([</span><spanclass="mi">12</span><spanclass="p">,</span><spanclass="o">-</span><spanclass="mf">14.23</span><spanclass="p">,</span><spanclass="s2">"hello"</span><spanclass="p">,</span><spanclass="kc">True</span><spanclass="p">,</span>
<spanclass="o">...</span><spanclass="s2">"Aha"</span><spanclass="p">,</span><spanclass="mf">10.1</span><spanclass="p">,</span><spanclass="kc">None</span><spanclass="p">,</span><spanclass="mi">5</span><spanclass="p">])</span>
<spanclass="o">>>></span><spanclass="n">s</span>
<spanclass="s1">'one-two | neg-one-four and float | hello | <OTHER> | Aha | one-zero and float | <OTHER> | five'</span>
</pre></div>
</div>
<p><strong>Tips</strong>: check out the <codeclass="docutils literal notranslate"><spanclass="pre">isinstance</span></code> function introduced <aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Basic_Objects.html">here</a> for handling different types. Also, consider creating a helper function for the conversion from integer to our special-format string, since we have to do it twice. It’s always good to extrapolate repeated tasks into functions. You’ll also need to hard-code the conversion from each digit to its English spell-out.</p>
<divclass="section" id="Solution">
<h2>Solution<aclass="headerlink" href="#Solution" title="Permalink to this headline"></a></h2>
<p>Our solution is broken down into three simple functions. <codeclass="docutils literal notranslate"><spanclass="pre">int_to_str</span></code> is used to map signed integers to English words. <codeclass="docutils literal notranslate"><spanclass="pre">item_to_transcript</span></code> is capable of mapping an object of any type to its string representation, in accordance with the prescription made by the problem statement. Finally, <codeclass="docutils literal notranslate"><spanclass="pre">concat_to_str</span></code> orchestrates these two helper functions, looping over each object in our input list, mapping each object to its string representation, and joining these strings with <codeclass="docutils literal notranslate"><spanclass="pre">'</span><spanclass="pre">|</span><spanclass="pre">'</span></code>.</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="k">def</span><spanclass="nf">int_to_str</span><spanclass="p">(</span><spanclass="n">n</span><spanclass="p">):</span>
<spanclass="sd">"""</span>
<spanclass="sd"> Takes an integer and formats it into a special string</span>
<spanclass="sd"> e.g. 142 -> "one-four-two"</span>
<spanclass="sd"> -12 -> "neg-one-two"</span>
<spanclass="sd"> """</span>
<spanclass="n">mapping</span><spanclass="o">=</span><spanclass="p">{</span><spanclass="s2">"0"</span><spanclass="p">:</span><spanclass="s2">"zero"</span><spanclass="p">,</span><spanclass="s2">"1"</span><spanclass="p">:</span><spanclass="s2">"one"</span><spanclass="p">,</span><spanclass="s2">"2"</span><spanclass="p">:</span><spanclass="s2">"two"</span><spanclass="p">,</span><spanclass="s2">"3"</span><spanclass="p">:</span><spanclass="s2">"three"</span><spanclass="p">,</span>
<spanclass="s2">"4"</span><spanclass="p">:</span><spanclass="s2">"four"</span><spanclass="p">,</span><spanclass="s2">"5"</span><spanclass="p">:</span><spanclass="s2">"five"</span><spanclass="p">,</span><spanclass="s2">"6"</span><spanclass="p">:</span><spanclass="s2">"six"</span><spanclass="p">,</span><spanclass="s2">"7"</span><spanclass="p">:</span><spanclass="s2">"seven"</span><spanclass="p">,</span>
<spanclass="s2">"8"</span><spanclass="p">:</span><spanclass="s2">"eight"</span><spanclass="p">,</span><spanclass="s2">"9"</span><spanclass="p">:</span><spanclass="s2">"nine"</span><spanclass="p">,</span><spanclass="s2">"-"</span><spanclass="p">:</span><spanclass="s2">"neg"</span><spanclass="p">}</span>
<spanclass="k">return</span><spanclass="s2">"-"</span><spanclass="o">.</span><spanclass="n">join</span><spanclass="p">(</span><spanclass="n">mapping</span><spanclass="p">[</span><spanclass="n">digit</span><spanclass="p">]</span><spanclass="k">for</span><spanclass="n">digit</span><spanclass="ow">in</span><spanclass="nb">str</span><spanclass="p">(</span><spanclass="n">n</span><spanclass="p">))</span>
<spanclass="k">def</span><spanclass="nf">item_to_transcript</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">):</span>
<spanclass="sd">""" Any -> str """</span>
<spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">bool</span><spanclass="p">):</span><spanclass="k">return</span><spanclass="s1">'<OTHER>'</span>
<spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">int</span><spanclass="p">):</span><spanclass="k">return</span><spanclass="n">int_to_str</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">)</span>
<spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">float</span><spanclass="p">):</span><spanclass="k">return</span><spanclass="n">int_to_str</span><spanclass="p">(</span><spanclass="nb">int</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">))</span><spanclass="o">+</span><spanclass="s2">" and float"</span>
<spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">str</span><spanclass="p">):</span><spanclass="k">return</span><spanclass="n">item</span>
<spanclass="k">return</span><spanclass="s1">'<OTHER>'</span>
<spanclass="k">def</span><spanclass="nf">concat_to_str</span><spanclass="p">(</span><spanclass="n">l</span><spanclass="p">):</span>
<spanclass="sd">"""</span>
<spanclass="sd"> Maps a list of objects to their string</span>
<spanclass="sd"> representations concatenated together.</span>
<spanclass="sd"> Parameters</span>
<spanclass="sd"> ----------</span>
<spanclass="sd"> l: List[Any]</span>
<spanclass="sd"> Input list of objects</span>
<spanclass="sd"> Returns</span>
<spanclass="sd"> -------</span>
<spanclass="sd"> str</span>
<spanclass="sd"> Examples</span>
<spanclass="sd"> --------</span>
<spanclass="sd"> >>> concat_to_str([1, None, 'hi', 2.0])</span>
<spanclass="sd"> one | <OTHER> | hi | two and float</span>
<spanclass="sd"> """</span>
<spanclass="k">return</span><spanclass="s2">" | "</span><spanclass="o">.</span><spanclass="n">join</span><spanclass="p">(</span><spanclass="n">item_to_transcript</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">)</span><spanclass="k">for</span><spanclass="n">item</span><spanclass="ow">in</span><spanclass="n">l</span><spanclass="p">)</span>
</pre></div>
</div>
<p>We use the <codeclass="docutils literal notranslate"><spanclass="pre">str.join</span></code> function along with a generator comprehensions in a couple places in our solution. Recall that</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="s2">"<hi>"</span><spanclass="o">.</span><spanclass="n">join</span><spanclass="p">(</span><spanclass="n">x</span><spanclass="k">for</span><spanclass="n">x</span><spanclass="ow">in</span><spanclass="n">some_iterable_of_strings</span><spanclass="p">)</span>
</pre></div>
</div>
<p>is equivalent to the long-form code:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="n">out</span><spanclass="o">=</span><spanclass="s2">""</span>
<spanclass="k">for</span><spanclass="n">x</span><spanclass="ow">in</span><spanclass="n">some_iterable_of_strings</span><spanclass="p">:</span>
<spanclass="n">out</span><spanclass="o">+=</span><spanclass="s2">"<hi>"</span><spanclass="o">+</span><spanclass="n">x</span>
<spanclass="n">out</span><spanclass="o">=</span><spanclass="n">out</span><spanclass="o">.</span><spanclass="n">lstrip</span><spanclass="p">(</span><spanclass="s2">"<hi>"</span><spanclass="p">)</span><spanclass="c1"># get rid of the extra leading "<hi>"</span>
</pre></div>
</div>
<p><codeclass="docutils literal notranslate"><spanclass="pre">int_to_str</span></code> plays a clever trick to convert each integer, digit-by-digit, into its string form - it calls <codeclass="docutils literal notranslate"><spanclass="pre">str</span></code> on the integer. This converts the integer into a string, which is a <aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/SequenceTypes.html">sequence</a>. This permits us to access each digit of the integer and even iterate over them:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="c1"># casting an integer to a string makes its</span>
<spanclass="c1"># sign and digits accessible via indexing/iteration</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="o">=</span><spanclass="nb">str</span><spanclass="p">(</span><spanclass="o">-</span><spanclass="mi">123</span><spanclass="p">)</span>
<spanclass="o">>>></span><spanclass="n">x</span>
<spanclass="s1">'-123'</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="p">[</span><spanclass="mi">0</span><spanclass="p">]</span>
<spanclass="s1">'-'</span>
<spanclass="o">>>></span><spanclass="n">x</span><spanclass="p">[</span><spanclass="o">-</span><spanclass="mi">1</span><spanclass="p">]</span>
<spanclass="s1">'3'</span>
</pre></div>
</div>
<p>Thus, in total <codeclass="docutils literal notranslate"><spanclass="pre">"-".join(mapping[digit]</span><spanclass="pre">for</span><spanclass="pre">digit</span><spanclass="pre">in</span><spanclass="pre">str(n))</span></code> is responsible for casting an integer to a string, iterating over each of its digits and mapping them to their corresponding word using the <aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/DataStructures_II_Dictionaries.html">dictionary</a> that we defined in the function.</p>
<p><codeclass="docutils literal notranslate"><spanclass="pre">item_to_transcript</span></code> it an especially slick function. First, let’s make clear the fancy use of the inline syntax here. This function:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="k">def</span><spanclass="nf">item_to_transcript</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">):</span>
<spanclass="sd">""" Any -> str """</span>
<spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">bool</span><spanclass="p">):</span><spanclass="k">return</span><spanclass="s1">'<OTHER>'</span>
<spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">int</span><spanclass="p">):</span><spanclass="k">return</span><spanclass="n">int_to_str</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">)</span>
<spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">float</span><spanclass="p">):</span><spanclass="k">return</span><spanclass="n">int_to_str</span><spanclass="p">(</span><spanclass="nb">int</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">))</span><spanclass="o">+</span><spanclass="s2">" and float"</span>
<spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">str</span><spanclass="p">):</span><spanclass="k">return</span><spanclass="n">item</span>
<spanclass="k">return</span><spanclass="s1">'<OTHER>'</span>
</pre></div>
</div>
<p>is entirely equivalent to this function:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="k">def</span><spanclass="nf">item_to_transcript_alt</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">):</span>
<spanclass="sd">""" Any -> str """</span>
<spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">bool</span><spanclass="p">):</span>
<spanclass="k">return</span><spanclass="s1">'<OTHER>'</span>
<spanclass="k">elif</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">int</span><spanclass="p">):</span>
<spanclass="k">return</span><spanclass="n">int_to_str</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">)</span>
<spanclass="k">elif</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">float</span><spanclass="p">):</span>
<spanclass="k">return</span><spanclass="n">int_to_str</span><spanclass="p">(</span><spanclass="nb">int</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">))</span><spanclass="o">+</span><spanclass="s2">" and float"</span>
<spanclass="k">elif</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">str</span><spanclass="p">):</span>
<spanclass="k">return</span><spanclass="n">item</span>
<spanclass="k">else</span><spanclass="p">:</span>
<spanclass="k">return</span><spanclass="s1">'<OTHER>'</span>
</pre></div>
</div>
<p>The latter uses the familiar pattern of <aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/ConditionalStatements.html">if-elif-else</a> statements and makes for a completely satisfactory version of the function. See, however, that each of the <aclass="reference external" href="https://www.pythonlikeyoumeanit.com/Module2_EssentialsOfPython/Functions.html#Multiple-return-Statements">multiple return statements</a> in <codeclass="docutils literal notranslate"><spanclass="pre">item_to_transcript</span></code> guarantees the same logic, in that if a condition is meant a value will be
returned by the function and none of its subsequent code can be visited. That is, if <codeclass="docutils literal notranslate"><spanclass="pre">item</span></code> is an integer the second if-condition will evaluate to <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">int_to_str(item)</span></code> will be returned, immediately expelling the point of execution from the body of the function.</p>
<p>Ultimately, the preference of one function over the other is merely a matter of stylistic preference. You also have likely noted the peculiar in-line <codeclass="docutils literal notranslate"><spanclass="pre">if-return</span></code> expressions. These too are only stylistic choices;</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">int</span><spanclass="p">):</span><spanclass="k">return</span><spanclass="n">int_to_str</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">)</span>
</pre></div>
</div>
<p>is no different from</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="k">if</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">,</span><spanclass="nb">int</span><spanclass="p">):</span>
<spanclass="k">return</span><spanclass="n">int_to_str</span><spanclass="p">(</span><spanclass="n">item</span><spanclass="p">)</span>
</pre></div>
</div>
<p>The use of in-line <codeclass="docutils literal notranslate"><spanclass="pre">if-return</span></code> expressions in <codeclass="docutils literal notranslate"><spanclass="pre">item_to_transcript</span></code> does a nice job emphasizing the dictionary-like mapping behavior of the function: the form of the code suits its functionality nicely. That being said, these should generally be used sparingly. Some may call this a “cute” trick. And it is. This code is cute. I write cute code.</p>
<p>Finally, you may have noticed what looks like a redundancy in our code: our first <codeclass="docutils literal notranslate"><spanclass="pre">if</span></code> statement returns <codeclass="docutils literal notranslate"><spanclass="pre">'<OTHER>'</span></code> if <codeclass="docutils literal notranslate"><spanclass="pre">item</span></code> is <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> or <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code>, and our final line of code returns <codeclass="docutils literal notranslate"><spanclass="pre">'<OTHER>'</span></code> if none of the preceding conditions were met (i.e. <codeclass="docutils literal notranslate"><spanclass="pre">item</span></code> is not a <codeclass="docutils literal notranslate"><spanclass="pre">bool</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">int</span></code>, <codeclass="docutils literal notranslate"><spanclass="pre">float</span></code>, or <codeclass="docutils literal notranslate"><spanclass="pre">str</span></code> type object). Why then did we not just merge our first <codeclass="docutils literal notranslate"><spanclass="pre">if</span></code> clause with this ultimate catch-all? The reason is that <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code> are not only instances of the boolean
type, they are also integers! <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> behaves like the integer <codeclass="docutils literal notranslate"><spanclass="pre">1</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code> like <codeclass="docutils literal notranslate"><spanclass="pre">0</span></code>:</p>
<divclass="highlight-python notranslate"><divclass="highlight"><pre><span></span><spanclass="gp">>>> </span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="kc">True</span><spanclass="p">,</span><spanclass="nb">int</span><spanclass="p">)</span><spanclass="ow">and</span><spanclass="nb">isinstance</span><spanclass="p">(</span><spanclass="kc">True</span><spanclass="p">,</span><spanclass="nb">bool</span><spanclass="p">)</span>
<spanclass="go">True</span>
<spanclass="gp">>>> </span><spanclass="mi">3</span><spanclass="o">*</span><spanclass="kc">True</span><spanclass="o">+</span><spanclass="kc">True</span><spanclass="o">-</span><spanclass="kc">False</span>
<spanclass="go">4</span>
</pre></div>
</div>
<p>Thus, had we not taken care to check for booleans up front, <codeclass="docutils literal notranslate"><spanclass="pre">True</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">False</span></code> would have been mapped to <codeclass="docutils literal notranslate"><spanclass="pre">'one'</span></code> and <codeclass="docutils literal notranslate"><spanclass="pre">'zero'</span></code>, respectively, rather than <codeclass="docutils literal notranslate"><spanclass="pre">'<OTHER>'</span></code>. This is a relatively subtle edge case to catch.</p>
</div>
</div>
</div>
</div>
<footer><divclass="rst-footer-buttons" role="navigation" aria-label="Footer">
<ahref="DifferenceFanout.html" class="btn btn-neutral float-left" title="Difference Fanout" accesskey="p" rel="prev"><spanclass="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a>
<ahref="../../module_3.html" class="btn btn-neutral float-right" title="Module 3: The Essentials of NumPy" accesskey="n" rel="next">Next <spanclass="fa fa-arrow-circle-right" aria-hidden="true"></span></a>
</div>
<hr/>
<divrole="contentinfo">
<p>© Copyright 2021, Ryan Soklaski.</p>
</div>
Built with <ahref="https://www.sphinx-doc.org/">Sphinx</a> using a
<ahref="https://github.com/readthedocs/sphinx_rtd_theme">theme</a>
provided by <ahref="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<script>
jQuery(function(){
SphinxRtdTheme.Navigation.enable(true);
});
</script>
</body>
</html>