-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path06-fruitful-fn.html
More file actions
717 lines (694 loc) · 48.9 KB
/
06-fruitful-fn.html
File metadata and controls
717 lines (694 loc) · 48.9 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Fruitful functions — Pense Python 2e documentation</title>
<link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '2e',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="Pense Python 2e documentation" href="index.html" />
<link rel="next" title="Iteration" href="07-iteration.html" />
<link rel="prev" title="Conditionals and recursion" href="05-cond-recur.html" />
<meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">
</head>
<body role="document">
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="fruitful-functions">
<h1>Fruitful functions<a class="headerlink" href="#fruitful-functions" title="Permalink to this headline">¶</a></h1>
<p>Many of the Python functions we have used, such as the math functions,
produce return values. But the functions we’ve written are all void:
they have an effect, like printing a value or moving a turtle, but they
don’t have a return value. In this chapter you will learn to write
fruitful functions.</p>
<div class="section" id="return-values">
<h2>Return values<a class="headerlink" href="#return-values" title="Permalink to this headline">¶</a></h2>
<p>Calling the function generates a return value, which we usually assign
to a variable or use as part of an expression.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">e</span> <span class="o">=</span> <span class="n">math</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="mf">1.0</span><span class="p">)</span>
<span class="n">height</span> <span class="o">=</span> <span class="n">radius</span> <span class="o">*</span> <span class="n">math</span><span class="o">.</span><span class="n">sin</span><span class="p">(</span><span class="n">radians</span><span class="p">)</span>
</pre></div>
</div>
<p>The functions we have written so far are void. Speaking casually, they
have no return value; more precisely, their return value is None.</p>
<p>In this chapter, we are (finally) going to write fruitful functions. The
first example is area, which returns the area of a circle with the given
radius:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">area</span><span class="p">(</span><span class="n">radius</span><span class="p">):</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">math</span><span class="o">.</span><span class="n">pi</span> <span class="o">*</span> <span class="n">radius</span><span class="o">**</span><span class="mi">2</span>
<span class="k">return</span> <span class="n">a</span>
</pre></div>
</div>
<p>We have seen the return statement before, but in a fruitful function the
return statement includes an expression. This statement means: “Return
immediately from this function and use the following expression as a
return value.” The expression can be arbitrarily complicated, so we
could have written this function more concisely:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">area</span><span class="p">(</span><span class="n">radius</span><span class="p">):</span>
<span class="k">return</span> <span class="n">math</span><span class="o">.</span><span class="n">pi</span> <span class="o">*</span> <span class="n">radius</span><span class="o">**</span><span class="mi">2</span>
</pre></div>
</div>
<p>On the other hand, <strong>temporary variables</strong> like a can make debugging
easier.</p>
<p>Sometimes it is useful to have multiple return statements, one in each
branch of a conditional:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">absolute_value</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="k">if</span> <span class="n">x</span> <span class="o"><</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="o">-</span><span class="n">x</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">x</span>
</pre></div>
</div>
<p>Since these return statements are in an alternative conditional, only
one runs.</p>
<p>As soon as a return statement runs, the function terminates without
executing any subsequent statements. Code that appears after a return
statement, or any other place the flow of execution can never reach, is
called <strong>dead code</strong>.</p>
<p>In a fruitful function, it is a good idea to ensure that every possible
path through the program hits a return statement. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">absolute_value</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="k">if</span> <span class="n">x</span> <span class="o"><</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="o">-</span><span class="n">x</span>
<span class="k">if</span> <span class="n">x</span> <span class="o">></span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="n">x</span>
</pre></div>
</div>
<p>This function is incorrect because if x happens to be 0, neither
condition is true, and the function ends without hitting a return
statement. If the flow of execution gets to the end of a function, the
return value is None, which is not the absolute value of 0.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">absolute_value</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
<p>By the way, Python provides a built-in function called abs that computes
absolute values.</p>
<p>As an exercise, write a compare function takes two values, x and y, and
returns 1 if x > y, 0 if x == y, and -1 if x < y.</p>
</div>
<div class="section" id="incremental-development">
<h2>Incremental development<a class="headerlink" href="#incremental-development" title="Permalink to this headline">¶</a></h2>
<p>As you write larger functions, you might find yourself spending more
time debugging.</p>
<p>To deal with increasingly complex programs, you might want to try a
process called <strong>incremental development</strong>. The goal of incremental
development is to avoid long debugging sessions by adding and testing
only a small amount of code at a time.</p>
<p>As an example, suppose you want to find the distance between two points,
given by the coordinates <span class="math">(x_1, y_1)</span> and <span class="math">(x_2, y_2)</span>. By
the Pythagorean theorem, the distance is:</p>
<div class="math">
<p><span class="math">\mathrm{distance} = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}</span></p>
</div><p>The first step is to consider what a distance function should look like
in Python. In other words, what are the inputs (parameters) and what is
the output (return value)?</p>
<p>In this case, the inputs are two points, which you can represent using
four numbers. The return value is the distance represented by a
floating-point value.</p>
<p>Immediately you can write an outline of the function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">distance</span><span class="p">(</span><span class="n">x1</span><span class="p">,</span> <span class="n">y1</span><span class="p">,</span> <span class="n">x2</span><span class="p">,</span> <span class="n">y2</span><span class="p">):</span>
<span class="k">return</span> <span class="mf">0.0</span>
</pre></div>
</div>
<p>Obviously, this version doesn’t compute distances; it always returns
zero. But it is syntactically correct, and it runs, which means that you
can test it before you make it more complicated.</p>
<p>To test the new function, call it with sample arguments:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">distance</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span>
<span class="go">0.0</span>
</pre></div>
</div>
<p>I chose these values so that the horizontal distance is 3 and the
vertical distance is 4; that way, the result is 5, the hypotenuse of a
3-4-5 triangle. When testing a function, it is useful to know the right
answer.</p>
<p>At this point we have confirmed that the function is syntactically
correct, and we can start adding code to the body. A reasonable next
step is to find the differences <span class="math">x_2 - x_1</span> and <span class="math">y_2 - y_1</span>.
The next version stores those values in temporary variables and prints
them.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">distance</span><span class="p">(</span><span class="n">x1</span><span class="p">,</span> <span class="n">y1</span><span class="p">,</span> <span class="n">x2</span><span class="p">,</span> <span class="n">y2</span><span class="p">):</span>
<span class="n">dx</span> <span class="o">=</span> <span class="n">x2</span> <span class="o">-</span> <span class="n">x1</span>
<span class="n">dy</span> <span class="o">=</span> <span class="n">y2</span> <span class="o">-</span> <span class="n">y1</span>
<span class="k">print</span><span class="p">(</span><span class="s">'dx is'</span><span class="p">,</span> <span class="n">dx</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="s">'dy is'</span><span class="p">,</span> <span class="n">dy</span><span class="p">)</span>
<span class="k">return</span> <span class="mf">0.0</span>
</pre></div>
</div>
<p>If the function is working, it should display <code class="docutils literal"><span class="pre">dx</span> <span class="pre">is</span> <span class="pre">3</span></code> and
<code class="docutils literal"><span class="pre">dy</span> <span class="pre">is</span> <span class="pre">4</span></code>. If so, we know that the function is getting the right
arguments and performing the first computation correctly. If not, there
are only a few lines to check.</p>
<p>Next we compute the sum of squares of dx and dy:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">distance</span><span class="p">(</span><span class="n">x1</span><span class="p">,</span> <span class="n">y1</span><span class="p">,</span> <span class="n">x2</span><span class="p">,</span> <span class="n">y2</span><span class="p">):</span>
<span class="n">dx</span> <span class="o">=</span> <span class="n">x2</span> <span class="o">-</span> <span class="n">x1</span>
<span class="n">dy</span> <span class="o">=</span> <span class="n">y2</span> <span class="o">-</span> <span class="n">y1</span>
<span class="n">dsquared</span> <span class="o">=</span> <span class="n">dx</span><span class="o">**</span><span class="mi">2</span> <span class="o">+</span> <span class="n">dy</span><span class="o">**</span><span class="mi">2</span>
<span class="k">print</span><span class="p">(</span><span class="s">'dsquared is: '</span><span class="p">,</span> <span class="n">dsquared</span><span class="p">)</span>
<span class="k">return</span> <span class="mf">0.0</span>
</pre></div>
</div>
<p>Again, you would run the program at this stage and check the output
(which should be 25). Finally, you can use math.sqrt to compute and
return the result:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">distance</span><span class="p">(</span><span class="n">x1</span><span class="p">,</span> <span class="n">y1</span><span class="p">,</span> <span class="n">x2</span><span class="p">,</span> <span class="n">y2</span><span class="p">):</span>
<span class="n">dx</span> <span class="o">=</span> <span class="n">x2</span> <span class="o">-</span> <span class="n">x1</span>
<span class="n">dy</span> <span class="o">=</span> <span class="n">y2</span> <span class="o">-</span> <span class="n">y1</span>
<span class="n">dsquared</span> <span class="o">=</span> <span class="n">dx</span><span class="o">**</span><span class="mi">2</span> <span class="o">+</span> <span class="n">dy</span><span class="o">**</span><span class="mi">2</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">dsquared</span><span class="p">)</span>
<span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>If that works correctly, you are done. Otherwise, you might want to
print the value of result before the return statement.</p>
<p>The final version of the function doesn’t display anything when it runs;
it only returns a value. The print statements we wrote are useful for
debugging, but once you get the function working, you should remove
them. Code like that is called <strong>scaffolding</strong> because it is helpful for
building the program but is not part of the final product.</p>
<p>When you start out, you should add only a line or two of code at a time.
As you gain more experience, you might find yourself writing and
debugging bigger chunks. Either way, incremental development can save
you a lot of debugging time.</p>
<p>The key aspects of the process are:</p>
<ol class="arabic simple">
<li>Start with a working program and make small incremental changes. At
any point, if there is an error, you should have a good idea where it
is.</li>
<li>Use variables to hold intermediate values so you can display and
check them.</li>
<li>Once the program is working, you might want to remove some of the
scaffolding or consolidate multiple statements into compound
expressions, but only if it does not make the program difficult to
read.</li>
</ol>
<p>As an exercise, use incremental development to write a function called
hypotenuse that returns the length of the hypotenuse of a right triangle
given the lengths of the other two legs as arguments. Record each stage
of the development process as you go.</p>
</div>
<div class="section" id="composition">
<h2>Composition<a class="headerlink" href="#composition" title="Permalink to this headline">¶</a></h2>
<p>As you should expect by now, you can call one function from within
another. As an example, we’ll write a function that takes two points,
the center of the circle and a point on the perimeter, and computes the
area of the circle.</p>
<p>Assume that the center point is stored in the variables xc and yc, and
the perimeter point is in xp and yp. The first step is to find the
radius of the circle, which is the distance between the two points. We
just wrote a function, distance, that does that:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">radius</span> <span class="o">=</span> <span class="n">distance</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span> <span class="n">yc</span><span class="p">,</span> <span class="n">xp</span><span class="p">,</span> <span class="n">yp</span><span class="p">)</span>
</pre></div>
</div>
<p>The next step is to find the area of a circle with that radius; we just
wrote that, too:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">result</span> <span class="o">=</span> <span class="n">area</span><span class="p">(</span><span class="n">radius</span><span class="p">)</span>
</pre></div>
</div>
<p>Encapsulating these steps in a function, we get:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">circle_area</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span> <span class="n">yc</span><span class="p">,</span> <span class="n">xp</span><span class="p">,</span> <span class="n">yp</span><span class="p">):</span>
<span class="n">radius</span> <span class="o">=</span> <span class="n">distance</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span> <span class="n">yc</span><span class="p">,</span> <span class="n">xp</span><span class="p">,</span> <span class="n">yp</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">area</span><span class="p">(</span><span class="n">radius</span><span class="p">)</span>
<span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>The temporary variables radius and result are useful for development and
debugging, but once the program is working, we can make it more concise
by composing the function calls:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">circle_area</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span> <span class="n">yc</span><span class="p">,</span> <span class="n">xp</span><span class="p">,</span> <span class="n">yp</span><span class="p">):</span>
<span class="k">return</span> <span class="n">area</span><span class="p">(</span><span class="n">distance</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span> <span class="n">yc</span><span class="p">,</span> <span class="n">xp</span><span class="p">,</span> <span class="n">yp</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="boolean-functions">
<h2>Boolean functions<a class="headerlink" href="#boolean-functions" title="Permalink to this headline">¶</a></h2>
<p>Functions can return booleans, which is often convenient for hiding
complicated tests inside functions. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">is_divisible</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="k">if</span> <span class="n">x</span> <span class="o">%</span> <span class="n">y</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">True</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="bp">False</span>
</pre></div>
</div>
<p>It is common to give boolean functions names that sound like yes/no
questions; <code class="docutils literal"><span class="pre">is_divisible</span></code> returns either True or False to indicate
whether x is divisible by y.</p>
<p>Here is an example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">is_divisible</span><span class="p">(</span><span class="mi">6</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="go">False</span>
<span class="gp">>>> </span><span class="n">is_divisible</span><span class="p">(</span><span class="mi">6</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>The result of the == operator is a boolean, so we can write the function
more concisely by returning it directly:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">is_divisible</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span> <span class="o">%</span> <span class="n">y</span> <span class="o">==</span> <span class="mi">0</span>
</pre></div>
</div>
<p>Boolean functions are often used in conditional statements:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">if</span> <span class="n">is_divisible</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="k">print</span><span class="p">(</span><span class="s">'x is divisible by y'</span><span class="p">)</span>
</pre></div>
</div>
<p>It might be tempting to write something like:</p>
<div class="highlight-python"><div class="highlight"><pre>if is_divisible(x, y) == True:
print('x is divisible by y'
</pre></div>
</div>
<p>But the extra comparison is unnecessary.</p>
<p>As an exercise, write a function <code class="docutils literal"><span class="pre">is_between(x,</span> <span class="pre">y,</span> <span class="pre">z)</span></code> that returns
True if <span class="math">x \le y \le z</span> or False otherwise.</p>
</div>
<div class="section" id="more-recursion">
<h2>More recursion<a class="headerlink" href="#more-recursion" title="Permalink to this headline">¶</a></h2>
<p>We have only covered a small subset of Python, but you might be
interested to know that this subset is a <em>complete</em> programming
language, which means that anything that can be computed can be
expressed in this language. Any program ever written could be rewritten
using only the language features you have learned so far (actually, you
would need a few commands to control devices like the mouse, disks,
etc., but that’s all).</p>
<p>Proving that claim is a nontrivial exercise first accomplished by Alan
Turing, one of the first computer scientists (some would argue that he
was a mathematician, but a lot of early computer scientists started as
mathematicians). Accordingly, it is known as the Turing Thesis. For a
more complete (and accurate) discussion of the Turing Thesis, I
recommend Michael Sipser’s book <em>Introduction to the Theory of
Computation</em>.</p>
<p>To give you an idea of what you can do with the tools you have learned
so far, we’ll evaluate a few recursively defined mathematical functions.
A recursive definition is similar to a circular definition, in the sense
that the definition contains a reference to the thing being defined. A
truly circular definition is not very useful:</p>
<dl class="docutils">
<dt>vorpal:</dt>
<dd>An adjective used to describe something that is vorpal.</dd>
</dl>
<p>If you saw that definition in the dictionary, you might be annoyed. On
the other hand, if you looked up the definition of the factorial
function, denoted with the symbol <span class="math">!</span>, you might get something
like this:</p>
<div class="math">
<p><span class="math">\begin{aligned}
&& 0! = 1 \\
&& n! = n (n-1)!\end{aligned}</span></p>
</div><p>This definition says that the factorial of 0 is 1, and the factorial of
any other value, <span class="math">n</span>, is <span class="math">n</span> multiplied by the factorial of
<span class="math">n-1</span>.</p>
<p>So <span class="math">3!</span> is 3 times <span class="math">2!</span>, which is 2 times <span class="math">1!</span>, which
is 1 times <span class="math">0!</span>. Putting it all together, <span class="math">3!</span> equals 3
times 2 times 1 times 1, which is 6.</p>
<p>If you can write a recursive definition of something, you can write a
Python program to evaluate it. The first step is to decide what the
parameters should be. In this case it should be clear that factorial
takes an integer:</p>
<div class="highlight-python"><div class="highlight"><pre>def factorial(n):
</pre></div>
</div>
<p>If the argument happens to be 0, all we have to do is return 1:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
</pre></div>
</div>
<p>Otherwise, and this is the interesting part, we have to make a recursive
call to find the factorial of <span class="math">n-1</span> and then multiply it by
<span class="math">n</span>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">recurse</span> <span class="o">=</span> <span class="n">factorial</span><span class="p">(</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">n</span> <span class="o">*</span> <span class="n">recurse</span>
<span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>The flow of execution for this program is similar to the flow of
countdown in Section [recursion]. If we call factorial with the value 3:</p>
<p>Since 3 is not 0, we take the second branch and calculate the factorial
of n-1...</p>
<blockquote>
<div><p>Since 2 is not 0, we take the second branch and calculate the
factorial of n-1...</p>
<blockquote>
<div><p>Since 1 is not 0, we take the second branch and calculate the
factorial of n-1...</p>
<blockquote>
<div>Since 0 equals 0, we take the first branch and return 1
without making any more recursive calls.</div></blockquote>
<p>The return value, 1, is multiplied by <span class="math">n</span>, which is 1, and
the result is returned.</p>
</div></blockquote>
<p>The return value, 1, is multiplied by <span class="math">n</span>, which is 2, and the
result is returned.</p>
</div></blockquote>
<p>The return value (2) is multiplied by <span class="math">n</span>, which is 3, and the
result, 6, becomes the return value of the function call that started
the whole process.</p>
<p>Figure [fig.stack3] shows what the stack diagram looks like for this
sequence of function calls.</p>
<div class="figure" id="id1">
<img alt="Stack diagram." src="_images/stack3.pdf" />
<p class="caption"><span class="caption-text">Stack diagram.</span></p>
</div>
<p>The return values are shown being passed back up the stack. In each
frame, the return value is the value of result, which is the product of
n and recurse.</p>
<p>In the last frame, the local variables recurse and result do not exist,
because the branch that creates them does not run.</p>
</div>
<div class="section" id="leap-of-faith">
<h2>Leap of faith<a class="headerlink" href="#leap-of-faith" title="Permalink to this headline">¶</a></h2>
<p>Following the flow of execution is one way to read programs, but it can
quickly become overwhelming. An alternative is what I call the “leap of
faith”. When you come to a function call, instead of following the flow
of execution, you <em>assume</em> that the function works correctly and returns
the right result.</p>
<p>In fact, you are already practicing this leap of faith when you use
built-in functions. When you call math.cos or math.exp, you don’t
examine the bodies of those functions. You just assume that they work
because the people who wrote the built-in functions were good
programmers.</p>
<p>The same is true when you call one of your own functions. For example,
in Section [boolean], we wrote a function called <code class="docutils literal"><span class="pre">is_divisible</span></code> that
determines whether one number is divisible by another. Once we have
convinced ourselves that this function is correct—by examining the code
and testing—we can use the function without looking at the body again.</p>
<p>The same is true of recursive programs. When you get to the recursive
call, instead of following the flow of execution, you should assume that
the recursive call works (returns the correct result) and then ask
yourself, “Assuming that I can find the factorial of <span class="math">n-1</span>, can I
compute the factorial of <span class="math">n</span>?” It is clear that you can, by
multiplying by <span class="math">n</span>.</p>
<p>Of course, it’s a bit strange to assume that the function works
correctly when you haven’t finished writing it, but that’s why it’s
called a leap of faith!</p>
</div>
<div class="section" id="one-more-example">
<h2>One more example<a class="headerlink" href="#one-more-example" title="Permalink to this headline">¶</a></h2>
<p>After factorial, the most common example of a recursively defined
mathematical function is fibonacci, which has the following definition
(see <a class="reference external" href="http://en.wikipedia.org/wiki/Fibonacci_number">http://en.wikipedia.org/wiki/Fibonacci_number</a>):</p>
<div class="math">
<p><span class="math">\begin{aligned}
&& \mathrm{fibonacci}(0) = 0 \\
&& \mathrm{fibonacci}(1) = 1 \\
&& \mathrm{fibonacci}(n) = \mathrm{fibonacci}(n-1) + \mathrm{fibonacci}(n-2)\end{aligned}</span></p>
</div><p>Translated into Python, it looks like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">fibonacci</span> <span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">0</span>
<span class="k">elif</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">fibonacci</span><span class="p">(</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="n">fibonacci</span><span class="p">(</span><span class="n">n</span><span class="o">-</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>If you try to follow the flow of execution here, even for fairly small
values of <span class="math">n</span>, your head explodes. But according to the leap of
faith, if you assume that the two recursive calls work correctly, then
it is clear that you get the right result by adding them together.</p>
</div>
<div class="section" id="checking-types">
<h2>Checking types<a class="headerlink" href="#checking-types" title="Permalink to this headline">¶</a></h2>
<p>What happens if we call factorial and give it 1.5 as an argument?</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">factorial</span><span class="p">(</span><span class="mf">1.5</span><span class="p">)</span>
<span class="go">RuntimeError: Maximum recursion depth exceeded</span>
</pre></div>
</div>
<p>It looks like an infinite recursion. How can that be? The function has a
base case—when n == 0. But if n is not an integer, we can <em>miss</em> the
base case and recurse forever.</p>
<p>In the first recursive call, the value of n is 0.5. In the next, it is
-0.5. From there, it gets smaller (more negative), but it will never be
0.</p>
<p>We have two choices. We can try to generalize the factorial function to
work with floating-point numbers, or we can make factorial check the
type of its argument. The first option is called the gamma function and
it’s a little beyond the scope of this book. So we’ll go for the second.</p>
<p>We can use the built-in function isinstance to verify the type of the
argument. While we’re at it, we can also make sure the argument is
positive:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">factorial</span> <span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="nb">int</span><span class="p">):</span>
<span class="k">print</span><span class="p">(</span><span class="s">'Factorial is only defined for integers.'</span><span class="p">)</span>
<span class="k">return</span> <span class="bp">None</span>
<span class="k">elif</span> <span class="n">n</span> <span class="o"><</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">print</span><span class="p">(</span><span class="s">'Factorial is not defined for negative integers.'</span><span class="p">)</span>
<span class="k">return</span> <span class="bp">None</span>
<span class="k">elif</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">n</span> <span class="o">*</span> <span class="n">factorial</span><span class="p">(</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>The first base case handles nonintegers; the second handles negative
integers. In both cases, the program prints an error message and returns
None to indicate that something went wrong:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">>>> </span><span class="n">factorial</span><span class="p">(</span><span class="s">'fred'</span><span class="p">)</span>
<span class="go">Factorial is only defined for integers.</span>
<span class="go">None</span>
<span class="gp">>>> </span><span class="n">factorial</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="p">)</span>
<span class="go">Factorial is not defined for negative integers.</span>
<span class="go">None</span>
</pre></div>
</div>
<p>If we get past both checks, we know that <span class="math">n</span> is positive or zero,
so we can prove that the recursion terminates.</p>
<p>This program demonstrates a pattern sometimes called a <strong>guardian</strong>. The
first two conditionals act as guardians, protecting the code that
follows from values that might cause an error. The guardians make it
possible to prove the correctness of the code.</p>
<p>In Section [raise] we will see a more flexible alternative to printing
an error message: raising an exception.</p>
</div>
<div class="section" id="debugging">
<h2>Debugging<a class="headerlink" href="#debugging" title="Permalink to this headline">¶</a></h2>
<p>Breaking a large program into smaller functions creates natural
checkpoints for debugging. If a function is not working, there are three
possibilities to consider:</p>
<ul class="simple">
<li>There is something wrong with the arguments the function is getting;
a precondition is violated.</li>
<li>There is something wrong with the function; a postcondition is
violated.</li>
<li>There is something wrong with the return value or the way it is being
used.</li>
</ul>
<p>To rule out the first possibility, you can add a print statement at the
beginning of the function and display the values of the parameters (and
maybe their types). Or you can write code that checks the preconditions
explicitly.</p>
<p>If the parameters look good, add a print statement before each return
statement and display the return value. If possible, check the result by
hand. Consider calling the function with values that make it easy to
check the result (as in Section [incremental.development]).</p>
<p>If the function seems to be working, look at the function call to make
sure the return value is being used correctly (or used at all!).</p>
<p>Adding print statements at the beginning and end of a function can help
make the flow of execution more visible. For example, here is a version
of factorial with print statements:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="n">space</span> <span class="o">=</span> <span class="s">' '</span> <span class="o">*</span> <span class="p">(</span><span class="mi">4</span> <span class="o">*</span> <span class="n">n</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">space</span><span class="p">,</span> <span class="s">'factorial'</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span>
<span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="k">print</span><span class="p">(</span><span class="n">space</span><span class="p">,</span> <span class="s">'returning 1'</span><span class="p">)</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">recurse</span> <span class="o">=</span> <span class="n">factorial</span><span class="p">(</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">n</span> <span class="o">*</span> <span class="n">recurse</span>
<span class="k">print</span><span class="p">(</span><span class="n">space</span><span class="p">,</span> <span class="s">'returning'</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>
<span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>space is a string of space characters that controls the indentation of
the output. Here is the result of factorial(4) :</p>
<div class="highlight-python"><div class="highlight"><pre> factorial 4
factorial 3
factorial 2
factorial 1
factorial 0
returning 1
returning 1
returning 2
returning 6
returning 24
</pre></div>
</div>
<p>If you are confused about the flow of execution, this kind of output can
be helpful. It takes some time to develop effective scaffolding, but a
little bit of scaffolding can save a lot of debugging.</p>
</div>
<div class="section" id="glossary">
<span id="glossary06"></span><h2>Glossary<a class="headerlink" href="#glossary" title="Permalink to this headline">¶</a></h2>
<dl class="docutils">
<dt>variável temporária (<em>temporary variable</em>)</dt>
<dd>A variable used to store an intermediate value in a complex calculation.</dd>
<dt>código morto (<em>dead code</em>)</dt>
<dd>Part of a program that can never run, often because it appears after a return statement.</dd>
<dt>desenvolvimento incremental (<em>incremental development</em>)</dt>
<dd>A program development plan intended to avoid debugging by adding and testing only a small amount of code at a time.</dd>
<dt>código provisório (<em>scaffolding</em>)</dt>
<dd>Code that is used during program development but is not part of the final version.</dd>
<dt>guarda (<em>guardian</em>)</dt>
<dd>A programming pattern that uses a conditional statement to check for and handle circumstances that might cause an error.</dd>
</dl>
</div>
<div class="section" id="exercises">
<h2>Exercises<a class="headerlink" href="#exercises" title="Permalink to this headline">¶</a></h2>
<p>Draw a stack diagram for the following program. What does the program
print?</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">b</span><span class="p">(</span><span class="n">z</span><span class="p">):</span>
<span class="n">prod</span> <span class="o">=</span> <span class="n">a</span><span class="p">(</span><span class="n">z</span><span class="p">,</span> <span class="n">z</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">z</span><span class="p">,</span> <span class="n">prod</span><span class="p">)</span>
<span class="k">return</span> <span class="n">prod</span>
<span class="k">def</span> <span class="nf">a</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span>
<span class="k">return</span> <span class="n">x</span> <span class="o">*</span> <span class="n">y</span>
<span class="k">def</span> <span class="nf">c</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span><span class="p">):</span>
<span class="n">total</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="o">+</span> <span class="n">z</span>
<span class="n">square</span> <span class="o">=</span> <span class="n">b</span><span class="p">(</span><span class="n">total</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span>
<span class="k">return</span> <span class="n">square</span>
<span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span>
<span class="k">print</span><span class="p">(</span><span class="n">c</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="o">+</span><span class="mi">3</span><span class="p">,</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">))</span>
</pre></div>
</div>
<p>[ackermann]</p>
<p>The Ackermann function, <span class="math">A(m, n)</span>, is defined:</p>
<div class="math">
<p><span class="math">\begin{aligned}
A(m, n) = \begin{cases}
n+1 & \mbox{if } m = 0 \\
A(m-1, 1) & \mbox{if } m > 0 \mbox{ and } n = 0 \\
A(m-1, A(m, n-1)) & \mbox{if } m > 0 \mbox{ and } n > 0.
\end{cases} \end{aligned}</span></p>
</div><p>See <a class="reference external" href="http://en.wikipedia.org/wiki/Ackermann_function">http://en.wikipedia.org/wiki/Ackermann_function</a>. Write a function
named ack that evaluates the Ackermann function. Use your function to
evaluate ack(3, 4), which should be 125. What happens for larger values
of m and n? Solution: <a class="reference external" href="http://thinkpython2.com/code/ackermann.py">http://thinkpython2.com/code/ackermann.py</a>.</p>
<p>[palindrome]</p>
<p>A palindrome is a word that is spelled the same backward and forward,
like “noon” and “redivider”. Recursively, a word is a palindrome if the
first and last letters are the same and the middle is a palindrome.</p>
<p>The following are functions that take a string argument and return the
first, last, and middle letters:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">first</span><span class="p">(</span><span class="n">word</span><span class="p">):</span>
<span class="k">return</span> <span class="n">word</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">last</span><span class="p">(</span><span class="n">word</span><span class="p">):</span>
<span class="k">return</span> <span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">middle</span><span class="p">(</span><span class="n">word</span><span class="p">):</span>
<span class="k">return</span> <span class="n">word</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
</pre></div>
</div>
<p>We’ll see how they work in Chapter [strings].</p>
<ol class="arabic simple">
<li>Type these functions into a file named palindrome.py and test them
out. What happens if you call middle with a string with two letters?
One letter? What about the empty string, which is written <code class="docutils literal"><span class="pre">''</span></code> and
contains no letters?</li>
<li>Write a function called <code class="docutils literal"><span class="pre">is_palindrome</span></code> that takes a string
argument and returns True if it is a palindrome and False otherwise.
Remember that you can use the built-in function len to check the
length of a string.</li>
</ol>
<p>Solution: <a class="reference external" href="http://thinkpython2.com/code/palindrome_soln.py">http://thinkpython2.com/code/palindrome_soln.py</a>.</p>
<p>A number, <span class="math">a</span>, is a power of <span class="math">b</span> if it is divisible by
<span class="math">b</span> and <span class="math">a/b</span> is a power of <span class="math">b</span>. Write a function
called <code class="docutils literal"><span class="pre">is_power</span></code> that takes parameters a and b and returns True if a
is a power of b. Note: you will have to think about the base case.</p>
<p>The greatest common divisor (GCD) of <span class="math">a</span> and <span class="math">b</span> is the
largest number that divides both of them with no remainder.</p>
<p>One way to find the GCD of two numbers is based on the observation that
if <span class="math">r</span> is the remainder when <span class="math">a</span> is divided by <span class="math">b</span>,
then <span class="math">gcd(a,
b) = gcd(b, r)</span>. As a base case, we can use <span class="math">gcd(a, 0) = a</span>.</p>
<p>Write a function called <code class="docutils literal"><span class="pre">gcd</span></code> that takes parameters a and b and
returns their greatest common divisor.</p>
<p>Credit: This exercise is based on an example from Abelson and Sussman’s
<em>Structure and Interpretation of Computer Programs</em>.</p>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<h3><a href="index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">Fruitful functions</a><ul>
<li><a class="reference internal" href="#return-values">Return values</a></li>
<li><a class="reference internal" href="#incremental-development">Incremental development</a></li>
<li><a class="reference internal" href="#composition">Composition</a></li>
<li><a class="reference internal" href="#boolean-functions">Boolean functions</a></li>
<li><a class="reference internal" href="#more-recursion">More recursion</a></li>
<li><a class="reference internal" href="#leap-of-faith">Leap of faith</a></li>
<li><a class="reference internal" href="#one-more-example">One more example</a></li>
<li><a class="reference internal" href="#checking-types">Checking types</a></li>
<li><a class="reference internal" href="#debugging">Debugging</a></li>
<li><a class="reference internal" href="#glossary">Glossary</a></li>
<li><a class="reference internal" href="#exercises">Exercises</a></li>
</ul>
</li>
</ul>
<div class="relations">
<h3>Related Topics</h3>
<ul>
<li><a href="index.html">Documentation overview</a><ul>
<li>Previous: <a href="05-cond-recur.html" title="previous chapter">Conditionals and recursion</a></li>
<li>Next: <a href="07-iteration.html" title="next chapter">Iteration</a></li>
</ul></li>
</ul>
</div>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/06-fruitful-fn.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer">
©2015, Allen B. Downey.
|
Powered by <a href="http://sphinx-doc.org/">Sphinx 1.3.1</a>
& <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.6</a>
|
<a href="_sources/06-fruitful-fn.txt"
rel="nofollow">Page source</a>
</div>
</body>
</html>