📚 The CoCalc Library - books, templates and other resources
License: OTHER
% LaTeX source for ``Think Python: How to Think Like a Computer Scientist''1% Copyright (c) 2015 Allen B. Downey.23% License: Creative Commons Attribution-NonCommercial 3.0 Unported License.4% http://creativecommons.org/licenses/by-nc/3.0/5%67%\documentclass[10pt,b5paper]{book}8\documentclass[10pt]{book}9\usepackage[width=5.5in,height=8.5in,hmarginratio=3:2,vmarginratio=1:1]{geometry}1011% for some of these packages, you might have to install12% texlive-latex-extra (in Ubuntu)1314\usepackage[T1]{fontenc}15\usepackage{textcomp}16\usepackage{mathpazo}17\usepackage{url}18\usepackage{fancyhdr}19\usepackage{graphicx}20\usepackage{amsmath}21\usepackage{amsthm}22%\usepackage{amssymb}23\usepackage{exercise} % texlive-latex-extra24\usepackage{makeidx}25\usepackage{setspace}26\usepackage{hevea}27\usepackage{upquote}28\usepackage{appendix}29\usepackage[bookmarks]{hyperref}3031\title{Think Python}32\author{Allen B. Downey}33\newcommand{\thetitle}{Think Python: How to Think Like a Computer Scientist}34\newcommand{\theversion}{2nd Edition, Version 2.4.0}35\newcommand{\thedate}{}3637% these styles get translated in CSS for the HTML version38\newstyle{a:link}{color:black;}39\newstyle{p+p}{margin-top:1em;margin-bottom:1em}40\newstyle{img}{border:0px}4142% change the arrows43\setlinkstext44{\imgsrc[ALT="Previous"]{back.png}}45{\imgsrc[ALT="Up"]{up.png}}46{\imgsrc[ALT="Next"]{next.png}}4748\makeindex4950\newif\ifplastex51\plastexfalse5253\begin{document}5455\frontmatter5657% PLASTEX ONLY58\ifplastex59\usepackage{localdef}60\maketitle6162\newcount\anchorcnt63\newcommand*{\Anchor}[1]{%64\@bsphack%65\Hy@GlobalStepCount\anchorcnt%66\edef\@currentHref{anchor.\the\anchorcnt}%67\Hy@raisedlink{\hyper@anchorstart{\@currentHref}\hyper@anchorend}%68\M@gettitle{}\label{#1}%69\@esphack%70}717273\else74% skip the following for plastex7576\newtheorem{exercise}{Exercise}[chapter]7778% LATEXONLY7980\input{latexonly}8182\begin{latexonly}8384\renewcommand{\blankpage}{\thispagestyle{empty} \quad \newpage}8586%\blankpage87%\blankpage8889% TITLE PAGES FOR LATEX VERSION9091%-half title--------------------------------------------------92\thispagestyle{empty}9394\begin{flushright}95\vspace*{2.0in}9697\begin{spacing}{3}98{\huge Think Python}\\99{\Large How to Think Like a Computer Scientist}100\end{spacing}101102\vspace{0.25in}103104\theversion105106\thedate107108\vfill109110\end{flushright}111112%--verso------------------------------------------------------113114\blankpage115\blankpage116%\clearemptydoublepage117%\pagebreak118%\thispagestyle{empty}119%\vspace*{6in}120121%--title page--------------------------------------------------122\pagebreak123\thispagestyle{empty}124125\begin{flushright}126\vspace*{2.0in}127128\begin{spacing}{3}129{\huge Think Python}\\130{\Large How to Think Like a Computer Scientist}131\end{spacing}132133\vspace{0.25in}134135\theversion136137\thedate138139\vspace{1in}140141142{\Large143Allen Downey\\144}145146147\vspace{0.5in}148149{\Large Green Tea Press}150151{\small Needham, Massachusetts}152153%\includegraphics[width=1in]{figs/logo1.pdf}154\vfill155156\end{flushright}157158159%--copyright--------------------------------------------------160\pagebreak161\thispagestyle{empty}162163{\small164Copyright \copyright ~2015 Allen Downey.165166167\vspace{0.2in}168169\begin{flushleft}170Green Tea Press \\1719 Washburn Ave \\172Needham MA 02492173\end{flushleft}174175Permission is granted to copy, distribute, and/or modify this document176under the terms of the Creative Commons Attribution-NonCommercial 3.0 Unported177License, which is available at \url{http://creativecommons.org/licenses/by-nc/3.0/}.178179The original form of this book is \LaTeX\ source code. Compiling this180\LaTeX\ source has the effect of generating a device-independent181representation of a textbook, which can be converted to other formats182and printed.183184The \LaTeX\ source for this book is available from185\url{http://www.thinkpython2.com}186187\vspace{0.2in}188189} % end small190191\end{latexonly}192193194% HTMLONLY195196\begin{htmlonly}197198% TITLE PAGE FOR HTML VERSION199200{\Large \thetitle}201202{\large Allen B. Downey}203204\theversion205206\thedate207208\setcounter{chapter}{-1}209210\end{htmlonly}211212\fi213% END OF THE PART WE SKIP FOR PLASTEX214215216\chapter{Preface}217218\section*{The strange history of this book}219220In January 1999 I was preparing to teach an introductory programming221class in Java. I had taught it three times and I was getting222frustrated. The failure rate in the class was too high and, even for223students who succeeded, the overall level of achievement was too low.224225One of the problems I saw was the books.226They were too big, with too much unnecessary detail about Java, and227not enough high-level guidance about how to program. And they all228suffered from the trap door effect: they would start out easy,229proceed gradually, and then somewhere around Chapter 5 the bottom would230fall out. The students would get too much new material, too fast,231and I would spend the rest of the semester picking up the pieces.232233Two weeks before the first day of classes, I decided to write my234own book. My goals were:235236\begin{itemize}237238\item Keep it short. It is better for students to read 10 pages239than not read 50 pages.240241\item Be careful with vocabulary. I tried to minimize jargon242and define each term at first use.243244\item Build gradually. To avoid trap doors, I took the most difficult245topics and split them into a series of small steps.246247\item Focus on programming, not the programming language. I included248the minimum useful subset of Java and left out the rest.249250\end{itemize}251252I needed a title, so on a whim I chose {\em How to Think Like253a Computer Scientist}.254255My first version was rough, but it worked. Students did the reading,256and they understood enough that I could spend class time on the hard257topics, the interesting topics and (most important) letting the258students practice.259260I released the book under the GNU Free Documentation License,261which allows users to copy, modify, and distribute the book.262\index{GNU Free Documentation License}263\index{Free Documentation License, GNU}264265What happened next is the cool part. Jeff Elkner, a high school266teacher in Virginia, adopted my book and translated it into267Python. He sent me a copy of his translation, and I had the268unusual experience of learning Python by reading my own book.269As Green Tea Press, I published the first Python version in 2001.270\index{Elkner, Jeff}271272In 2003 I started teaching at Olin College and I got to teach273Python for the first time. The contrast with Java was striking.274Students struggled less, learned more, worked on more interesting275projects, and generally had a lot more fun.276\index{Olin College}277278Since then I've continued to develop the book,279correcting errors, improving some of the examples and280adding material, especially exercises.281282The result is this book, now with the less grandiose title283{\em Think Python}. Some of the changes are:284285\begin{itemize}286287\item I added a section about debugging at the end of each chapter.288These sections present general techniques for finding and avoiding289bugs, and warnings about Python pitfalls.290291\item I added more exercises, ranging from short tests of292understanding to a few substantial projects. Most exercises293include a link to my solution.294295\item I added a series of case studies---longer examples with296exercises, solutions, and discussion.297298\item I expanded the discussion of program development plans299and basic design patterns.300301\item I added appendices about debugging and analysis of algorithms.302303\end{itemize}304305The second edition of {\em Think Python} has these new features:306307\begin{itemize}308309\item The book and all supporting code have been updated to Python 3.310311\item I added a few sections, and more details on the web, to help312beginners get started running Python in a browser, so you don't have313to deal with installing Python until you want to.314315\item For Chapter~\ref{turtle} I switched from my own turtle graphics316package, called Swampy, to a more standard Python module, {\tt317turtle}, which is easier to install and more powerful.318319\item I added a new chapter called ``The Goodies'', which introduces320some additional Python features that are not strictly necessary, but321sometimes handy.322323\end{itemize}324325I hope you enjoy working with this book, and that it helps326you learn to program and think like327a computer scientist, at least a little bit.328329330Allen B. Downey \\331332Olin College \\333334335\section*{Acknowledgments}336337Many thanks to Jeff Elkner, who338translated my Java book into Python, which got this project339started and introduced me to what has turned out to be my340favorite language.341\index{Elkner, Jeff}342343Thanks also to Chris Meyers, who contributed several sections344to {\em How to Think Like a Computer Scientist}.345\index{Meyers, Chris}346347Thanks to the Free Software Foundation for developing348the GNU Free Documentation License, which helped make349my collaboration with Jeff and Chris possible, and Creative350Commons for the license I am using now.351\index{GNU Free Documentation License}352\index{Free Documentation License, GNU}353\index{Creative Commons}354355Thanks to the editors at Lulu who worked on356{\em How to Think Like a Computer Scientist}.357358Thanks to the editors at O'Reilly Media who worked on359{\em Think Python}.360361Thanks to all the students who worked with earlier362versions of this book and all the contributors (listed363below) who sent in corrections and suggestions.364365366\section*{Contributor List}367368\index{contributors}369More than 100 sharp-eyed and thoughtful readers have sent in370suggestions and corrections over the past few years. Their371contributions, and enthusiasm for this project, have been a372huge help.373374If you have a suggestion or correction, please send email to375{\tt feedback@thinkpython.com}. If I make a change based on your376feedback, I will add you to the contributor list377(unless you ask to be omitted).378379If you include at least part of the sentence the380error appears in, that makes it easy for me to search. Page and381section numbers are fine, too, but not quite as easy to work with.382Thanks!383384\begin{itemize}385386\small387\item Lloyd Hugh Allen sent in a correction to Section 8.4.388389\item Yvon Boulianne sent in a correction of a semantic error in390Chapter 5.391392\item Fred Bremmer submitted a correction in Section 2.1.393394\item Jonah Cohen wrote the Perl scripts to convert the395LaTeX source for this book into beautiful HTML.396397\item Michael Conlon sent in a grammar correction in Chapter 2398and an improvement in style in Chapter 1, and he initiated discussion399on the technical aspects of interpreters.400401\item Beno\^{i}t Girard sent in a402correction to a humorous mistake in Section 5.6.403404\item Courtney Gleason and Katherine Smith wrote {\tt horsebet.py},405which was used as a case study in an earlier version of the book. Their406program can now be found on the website.407408\item Lee Harr submitted more corrections than we have room to list409here, and indeed he should be listed as one of the principal editors410of the text.411412\item James Kaylin is a student using the text. He has submitted413numerous corrections.414415\item David Kershaw fixed the broken {\tt catTwice} function in Section4163.10.417418\item Eddie Lam has sent in numerous corrections to Chapters4191, 2, and 3.420He also fixed the Makefile so that it creates an index the first time it is421run and helped us set up a versioning scheme.422423\item Man-Yong Lee sent in a correction to the example code in424Section 2.4.425426\item David Mayo pointed out that the word ``unconsciously"427in Chapter 1 needed428to be changed to ``subconsciously".429430\item Chris McAloon sent in several corrections to Sections 3.9 and4313.10.432433\item Matthew J. Moelter has been a long-time contributor who sent434in numerous corrections and suggestions to the book.435436\item Simon Dicon Montford reported a missing function definition and437several typos in Chapter 3. He also found errors in the {\tt increment}438function in Chapter 13.439440\item John Ouzts corrected the definition of ``return value"441in Chapter 3.442443\item Kevin Parks sent in valuable comments and suggestions as to how444to improve the distribution of the book.445446\item David Pool sent in a typo in the glossary of Chapter 1, as well447as kind words of encouragement.448449\item Michael Schmitt sent in a correction to the chapter on files450and exceptions.451452\item Robin Shaw pointed out an error in Section 13.1, where the453printTime function was used in an example without being defined.454455\item Paul Sleigh found an error in Chapter 7 and a bug in Jonah Cohen's456Perl script that generates HTML from LaTeX.457458\item Craig T. Snydal is testing the text in a course at Drew459University. He has contributed several valuable suggestions and corrections.460461\item Ian Thomas and his students are using the text in a programming462course. They are the first ones to test the chapters in the latter half463of the book, and they have made numerous corrections and suggestions.464465\item Keith Verheyden sent in a correction in Chapter 3.466467\item Peter Winstanley let us know about a longstanding error in468our Latin in Chapter 3.469470\item Chris Wrobel made corrections to the code in the chapter on471file I/O and exceptions.472473\item Moshe Zadka has made invaluable contributions to this project.474In addition to writing the first draft of the chapter on Dictionaries, he475provided continual guidance in the early stages of the book.476477\item Christoph Zwerschke sent several corrections and478pedagogic suggestions, and explained the difference between {\em gleich}479and {\em selbe}.480481\item James Mayer sent us a whole slew of spelling and482typographical errors, including two in the contributor list.483484\item Hayden McAfee caught a potentially confusing inconsistency485between two examples.486487\item Angel Arnal is part of an international team of translators488working on the Spanish version of the text. He has also found several489errors in the English version.490491\item Tauhidul Hoque and Lex Berezhny created the illustrations492in Chapter 1 and improved many of the other illustrations.493494\item Dr. Michele Alzetta caught an error in Chapter 8 and sent495some interesting pedagogic comments and suggestions about Fibonacci496and Old Maid.497498\item Andy Mitchell caught a typo in Chapter 1 and a broken example499in Chapter 2.500501\item Kalin Harvey suggested a clarification in Chapter 7 and502caught some typos.503504\item Christopher P. Smith caught several typos and helped us505update the book for Python 2.2.506507\item David Hutchins caught a typo in the Foreword.508509\item Gregor Lingl is teaching Python at a high school in Vienna,510Austria. He is working on a German translation of the book,511and he caught a couple of bad errors in Chapter 5.512513\item Julie Peters caught a typo in the Preface.514515\item Florin Oprina sent in an improvement in {\tt makeTime},516a correction in {\tt printTime}, and a nice typo.517518\item D.~J.~Webre suggested a clarification in Chapter 3.519520\item Ken found a fistful of errors in Chapters 8, 9 and 11.521522\item Ivo Wever caught a typo in Chapter 5 and suggested a clarification523in Chapter 3.524525\item Curtis Yanko suggested a clarification in Chapter 2.526527\item Ben Logan sent in a number of typos and problems with translating528the book into HTML.529530\item Jason Armstrong saw the missing word in Chapter 2.531532\item Louis Cordier noticed a spot in Chapter 16 where the code533didn't match the text.534535\item Brian Cain suggested several clarifications in Chapters 2 and 3.536537\item Rob Black sent in a passel of corrections, including some538changes for Python 2.2.539540\item Jean-Philippe Rey at \'{E}cole Centrale541Paris sent a number of patches, including some updates for Python 2.2542and other thoughtful improvements.543544\item Jason Mader at George Washington University made a number545of useful suggestions and corrections.546547\item Jan Gundtofte-Bruun reminded us that ``a error'' is an error.548549\item Abel David and Alexis Dinno reminded us that the plural of550``matrix'' is ``matrices'', not ``matrixes''. This error was in the551book for years, but two readers with the same initials reported it on552the same day. Weird.553554\item Charles Thayer encouraged us to get rid of the semi-colons555we had put at the ends of some statements and to clean up our556use of ``argument'' and ``parameter''.557558\item Roger Sperberg pointed out a twisted piece of logic in Chapter 3.559560\item Sam Bull pointed out a confusing paragraph in Chapter 2.561562\item Andrew Cheung pointed out two instances of ``use before def''.563564\item C. Corey Capel spotted the missing word in the Third Theorem565of Debugging and a typo in Chapter 4.566567\item Alessandra helped clear up some Turtle confusion.568569\item Wim Champagne found a brain-o in a dictionary example.570571\item Douglas Wright pointed out a problem with floor division in572{\tt arc}.573574\item Jared Spindor found some jetsam at the end of a sentence.575576\item Lin Peiheng sent a number of very helpful suggestions.577578\item Ray Hagtvedt sent in two errors and a not-quite-error.579580\item Torsten H\"{u}bsch pointed out an inconsistency in Swampy.581582\item Inga Petuhhov corrected an example in Chapter 14.583584\item Arne Babenhauserheide sent several helpful corrections.585586\item Mark E. Casida is is good at spotting repeated words.587588\item Scott Tyler filled in a that was missing. And then sent in589a heap of corrections.590591\item Gordon Shephard sent in several corrections, all in separate592emails.593594\item Andrew Turner {\tt spot}ted an error in Chapter 8.595596\item Adam Hobart fixed a problem with floor division in {\tt arc}.597598\item Daryl Hammond and Sarah Zimmerman pointed out that I served599up {\tt math.pi} too early. And Zim spotted a typo.600601\item George Sass found a bug in a Debugging section.602603\item Brian Bingham suggested Exercise~\ref{exrotatepairs}.604605\item Leah Engelbert-Fenton pointed out that I used {\tt tuple}606as a variable name, contrary to my own advice. And then found607a bunch of typos and a ``use before def''.608609\item Joe Funke spotted a typo.610611\item Chao-chao Chen found an inconsistency in the Fibonacci example.612613\item Jeff Paine knows the difference between space and spam.614615\item Lubos Pintes sent in a typo.616617\item Gregg Lind and Abigail Heithoff suggested Exercise~\ref{checksum}.618619\item Max Hailperin has sent in a number of corrections and620suggestions. Max is one of the authors of the extraordinary {\em621Concrete Abstractions}, which you might want to read when you are622done with this book.623624\item Chotipat Pornavalai found an error in an error message.625626\item Stanislaw Antol sent a list of very helpful suggestions.627628\item Eric Pashman sent a number of corrections for Chapters 4--11.629630\item Miguel Azevedo found some typos.631632\item Jianhua Liu sent in a long list of corrections.633634\item Nick King found a missing word.635636\item Martin Zuther sent a long list of suggestions.637638\item Adam Zimmerman found an inconsistency in my instance639of an ``instance'' and several other errors.640641\item Ratnakar Tiwari suggested a footnote explaining degenerate642triangles.643644\item Anurag Goel suggested another solution for \verb"is_abecedarian"645and sent some additional corrections. And he knows how to646spell Jane Austen.647648\item Kelli Kratzer spotted one of the typos.649650\item Mark Griffiths pointed out a confusing example in Chapter 3.651652\item Roydan Ongie found an error in my Newton's method.653654\item Patryk Wolowiec helped me with a problem in the HTML version.655656\item Mark Chonofsky told me about a new keyword in Python 3.657658\item Russell Coleman helped me with my geometry.659660\item Nam Nguyen found a typo and pointed out that I used the Decorator661pattern but didn't mention it by name.662663\item St\'{e}phane Morin sent in several corrections and suggestions.664665\item Paul Stoop corrected a typo in \verb+uses_only+.666667\item Eric Bronner pointed out a confusion in the discussion of the668order of operations.669670\item Alexandros Gezerlis set a new standard for the number and671quality of suggestions he submitted. We are deeply grateful!672673\item Gray Thomas knows his right from his left.674675\item Giovanni Escobar Sosa sent a long list of corrections and676suggestions.677678\item Daniel Neilson corrected an error about the order of operations.679680\item Will McGinnis pointed out that {\tt polyline} was defined681differently in two places.682683\item Frank Hecker pointed out an exercise that was under-specified, and684some broken links.685686\item Animesh B helped me clean up a confusing example.687688\item Martin Caspersen found two round-off errors.689690\item Gregor Ulm sent several corrections and suggestions.691692\item Dimitrios Tsirigkas suggested I clarify an exercise.693694\item Carlos Tafur sent a page of corrections and suggestions.695696\item Martin Nordsletten found a bug in an exercise solution.697698\item Sven Hoexter pointed out that a variable named {\tt input}699shadows a build-in function.700701\item Stephen Gregory pointed out the problem with {\tt cmp}702in Python 3.703704\item Ishwar Bhat corrected my statement of Fermat's last theorem.705706\item Andrea Zanella translated the book into Italian, and sent a707number of corrections along the way.708709\item Many, many thanks to Melissa Lewis and Luciano Ramalho for710excellent comments and suggestions on the second edition.711712\item Thanks to Harry Percival from PythonAnywhere for his help713getting people started running Python in a browser.714715\item Xavier Van Aubel made several useful corrections in the second716edition.717718\item William Murray corrected my definition of floor division.719720\item Per Starb{\"a}ck brought me up to date on universal newlines in Python 3.721722\item Laurent Rosenfeld and Mihaela Rotaru translated this book into French. Along the way, they sent many corrections and suggestions.723724% ENDCONTRIB725726In addition, people who spotted typos or made corrections include727Czeslaw Czapla, Dale Wilson, Francesco Carlo Cimini,728Richard Fursa, Brian McGhie, Lokesh Kumar Makani, Matthew Shultz, Viet729Le, Victor Simeone, Lars O.D. Christensen, Swarup Sahoo, Alix Etienne,730Kuang He, Wei Huang, Karen Barber, and Eric Ransom.731732733734735\end{itemize}736737\normalsize738\clearemptydoublepage739740% TABLE OF CONTENTS741\begin{latexonly}742743\tableofcontents744745\clearemptydoublepage746747\end{latexonly}748749% START THE BOOK750\mainmatter751752\chapter{The way of the program}753754The goal of this book is to teach you to think like a computer755scientist. This way of thinking combines some of the best features of756mathematics, engineering, and natural science. Like mathematicians,757computer scientists use formal languages to denote ideas (specifically758computations). Like engineers, they design things, assembling759components into systems and evaluating tradeoffs among alternatives.760Like scientists, they observe the behavior of complex systems, form761hypotheses, and test predictions. \index{problem solving}762763The single most important skill for a computer scientist is {\bf764problem solving}. Problem solving means the ability to formulate765problems, think creatively about solutions, and express a solution766clearly and accurately. As it turns out, the process of learning to767program is an excellent opportunity to practice problem-solving768skills. That's why this chapter is called, ``The way of the769program''.770771On one level, you will be learning to program, a useful skill by772itself. On another level, you will use programming as a means to an773end. As we go along, that end will become clearer.774775776\section{What is a program?}777778A {\bf program} is a sequence of instructions that specifies how to779perform a computation. The computation might be something780mathematical, such as solving a system of equations or finding the781roots of a polynomial, but it can also be a symbolic computation, such782as searching and replacing text in a document or something783graphical, like processing an image or playing a video.784\index{program}785786The details look different in different languages, but a few basic787instructions appear in just about every language:788789\begin{description}790791\item[input:] Get data from the keyboard, a file, the network, or some792other device.793794\item[output:] Display data on the screen, save it in a795file, send it over the network, etc.796797\item[math:] Perform basic mathematical operations like addition and798multiplication.799800\item[conditional execution:] Check for certain conditions and801run the appropriate code.802803\item[repetition:] Perform some action repeatedly, usually with804some variation.805806\end{description}807808Believe it or not, that's pretty much all there is to it. Every809program you've ever used, no matter how complicated, is made up of810instructions that look pretty much like these. So you can think of811programming as the process of breaking a large, complex task812into smaller and smaller subtasks until the subtasks are813simple enough to be performed with one of these basic instructions.814815816\section{Running Python}817818One of the challenges of getting started with Python is that you819might have to install Python and related software on your computer.820If you are familiar with your operating system, and especially821if you are comfortable with the command-line interface, you will822have no trouble installing Python. But for beginners, it can be823painful to learn about system administration and programming at the824same time.825\index{running Python}826\index{Python!running}827828To avoid that problem, I recommend that you start out running Python829in a browser. Later, when you are comfortable with Python, I'll830make suggestions for installing Python on your computer.831\index{Python in a browser}832833There are a number of web pages you can use to run Python. If you834already have a favorite, go ahead and use it. Otherwise I recommend835PythonAnywhere. I provide detailed instructions for getting started836at \url{http://tinyurl.com/thinkpython2e}.837\index{PythonAnywhere}838839There are two versions of Python, called Python 2 and Python 3.840They are very similar, so if you learn one, it is easy to switch841to the other. In fact, there are only a few differences you will842encounter as a beginner.843This book is written for Python 3, but I include some notes844about Python 2.845\index{Python 2}846847The Python {\bf interpreter} is a program that reads and executes848Python code. Depending on your environment, you might start the849interpreter by clicking on an icon, or by typing {\tt python} on850a command line.851When it starts, you should see output like this:852\index{interpreter}853854\begin{verbatim}855Python 3.4.0 (default, Jun 19 2015, 14:20:21)856[GCC 4.8.2] on linux857Type "help", "copyright", "credits" or "license" for more information.858>>>859\end{verbatim}860%861The first three lines contain information about the interpreter862and the operating system it's running on, so it might be different for863you. But you should check that the version number, which is864{\tt 3.4.0} in this example, begins with 3, which indicates that865you are running Python 3. If it begins with 2, you are running866(you guessed it) Python 2.867868The last line is a {\bf prompt} that indicates that the interpreter is869ready for you to enter code.870If you type a line of code and hit Enter, the interpreter displays the871result:872\index{prompt}873874\begin{verbatim}875>>> 1 + 18762877\end{verbatim}878%879Now you're ready to get started.880From here on, I assume that you know how to start the Python881interpreter and run code.882883884\section{The first program}885\label{hello}886\index{Hello, World}887888Traditionally, the first program you write in a new language889is called ``Hello, World!'' because all it does is display the890words ``Hello, World!''. In Python, it looks like this:891892\begin{verbatim}893>>> print('Hello, World!')894\end{verbatim}895%896This is an example of a {\bf print statement}, although it897doesn't actually print anything on paper. It displays a result on the898screen. In this case, the result is the words899900\begin{verbatim}901Hello, World!902\end{verbatim}903%904The quotation marks in the program mark the beginning and end905of the text to be displayed; they don't appear in the result.906\index{quotation mark}907\index{print statement}908\index{statement!print}909910The parentheses indicate that {\tt print} is a function. We'll get911to functions in Chapter~\ref{funcchap}.912\index{function} \index{print function}913914In Python 2, the print statement is slightly different; it is not915a function, so it doesn't use parentheses.916\index{Python 2}917918\begin{verbatim}919>>> print 'Hello, World!'920\end{verbatim}921%922This distinction will make more sense soon, but that's enough to923get started.924925926\section{Arithmetic operators}927\index{operator!arithmetic}928\index{arithmetic operator}929930After ``Hello, World'', the next step is arithmetic. Python provides931{\bf operators}, which are special symbols that represent computations932like addition and multiplication.933934The operators {\tt +}, {\tt -}, and {\tt *} perform addition,935subtraction, and multiplication, as in the following examples:936937\begin{verbatim}938>>> 40 + 293942940>>> 43 - 194142942>>> 6 * 794342944\end{verbatim}945%946The operator {\tt /} performs division:947948\begin{verbatim}949>>> 84 / 295042.0951\end{verbatim}952%953You might wonder why the result is {\tt 42.0} instead of {\tt 42}.954I'll explain in the next section.955956Finally, the operator {\tt **} performs exponentiation; that is,957it raises a number to a power:958959\begin{verbatim}960>>> 6**2 + 696142962\end{verbatim}963%964In some other languages, \verb"^" is used for exponentiation, but965in Python it is a bitwise operator called XOR. If you are not966familiar with bitwise operators, the result will surprise you:967968\begin{verbatim}969>>> 6 ^ 29704971\end{verbatim}972%973I won't cover974bitwise operators in this book, but you can read about975them at \url{http://wiki.python.org/moin/BitwiseOperators}.976\index{bitwise operator}977\index{operator!bitwise}978979980\section{Values and types}981\index{value}982\index{type}983\index{string}984985A {\bf value} is one of the basic things a program works with, like a986letter or a number. Some values we have seen so far are {\tt 2},987{\tt 42.0}, and \verb"'Hello, World!'".988989These values belong to different {\bf types}:990{\tt 2} is an {\bf integer}, {\tt 42.0} is a {\bf floating-point number},991and \verb"'Hello, World!'" is a {\bf string},992so-called because the letters it contains are strung together.993\index{integer}994\index{floating-point}995996If you are not sure what type a value has, the interpreter can997tell you:998999\begin{verbatim}1000>>> type(2)1001<class 'int'>1002>>> type(42.0)1003<class 'float'>1004>>> type('Hello, World!')1005<class 'str'>1006\end{verbatim}1007%1008In these results, the word ``class'' is used in the sense of1009a category; a type is a category of values.1010\index{class}10111012Not surprisingly, integers belong to the type {\tt int},1013strings belong to {\tt str} and floating-point1014numbers belong to {\tt float}.1015\index{type}1016\index{string type}1017\index{type!str}1018\index{int type}1019\index{type!int}1020\index{float type}1021\index{type!float}10221023What about values like \verb"'2'" and \verb"'42.0'"?1024They look like numbers, but they are in quotation marks like1025strings.1026\index{quotation mark}10271028\begin{verbatim}1029>>> type('2')1030<class 'str'>1031>>> type('42.0')1032<class 'str'>1033\end{verbatim}1034%1035They're strings.10361037When you type a large integer, you might be tempted to use commas1038between groups of digits, as in {\tt 1,000,000}. This is not a1039legal {\em integer} in Python, but it is legal:10401041\begin{verbatim}1042>>> 1,000,0001043(1, 0, 0)1044\end{verbatim}1045%1046That's not what we expected at all! Python interprets {\tt10471,000,000} as a comma-separated sequence of integers. We'll learn1048more about this kind of sequence later.1049\index{sequence}10501051%This is the first example we have seen of a semantic error: the code1052%runs without producing an error message, but it doesn't do the1053%``right'' thing.1054%\index{semantic error}1055%\index{error!semantic}1056%\index{error message}1057% TODO: use this as an example of a semantic error later1058105910601061\section{Formal and natural languages}1062\index{formal language}1063\index{natural language}1064\index{language!formal}1065\index{language!natural}10661067{\bf Natural languages} are the languages people speak,1068such as English, Spanish, and French. They were not designed1069by people (although people try to impose some order on them);1070they evolved naturally.10711072{\bf Formal languages} are languages that are designed by people for1073specific applications. For example, the notation that mathematicians1074use is a formal language that is particularly good at denoting1075relationships among numbers and symbols. Chemists use a formal1076language to represent the chemical structure of molecules. And1077most importantly:10781079\begin{quote}1080{\bf Programming languages are formal languages that have been1081designed to express computations.}1082\end{quote}10831084Formal languages tend to have strict {\bf syntax} rules that1085govern the structure of statements.1086For example, in mathematics the statement1087$3 + 3 = 6$ has correct syntax, but1088$3 + = 3 \$ 6$ does not. In chemistry1089$H_2O$ is a syntactically correct formula, but $_2Zz$ is not.1090\index{syntax}10911092Syntax rules come in two flavors, pertaining to {\bf tokens} and1093structure. Tokens are the basic elements of the language, such as1094words, numbers, and chemical elements. One of the problems with1095$3 += 3 \$ 6$ is that \( \$ \) is not a legal token in mathematics1096(at least as far as I know). Similarly, $_2Zz$ is not legal because1097there is no element with the abbreviation $Zz$.1098\index{token}1099\index{structure}11001101The second type of syntax rule pertains to the way tokens are1102combined. The equation $3 +/ 3$ is illegal because even though $+$1103and $/$ are legal tokens, you can't have one right after the other.1104Similarly, in a chemical formula the subscript comes after the element1105name, not before.11061107This is @ well-structured Engli\$h1108sentence with invalid t*kens in it. This sentence all valid tokens1109has, but invalid structure with.11101111When you read a sentence in English or a statement in a formal1112language, you have to figure out the structure1113(although in a natural language you do this subconsciously). This1114process is called {\bf parsing}.1115\index{parse}11161117Although formal and natural languages have many features in1118common---tokens, structure, and syntax---there are some1119differences:1120\index{ambiguity}1121\index{redundancy}1122\index{literalness}11231124\begin{description}11251126\item[ambiguity:] Natural languages are full of ambiguity, which1127people deal with by using contextual clues and other information.1128Formal languages are designed to be nearly or completely unambiguous,1129which means that any statement has exactly one meaning,1130regardless of context.11311132\item[redundancy:] In order to make up for ambiguity and reduce1133misunderstandings, natural languages employ lots of1134redundancy. As a result, they are often verbose. Formal languages1135are less redundant and more concise.11361137\item[literalness:] Natural languages are full of idiom and metaphor.1138If I say, ``The penny dropped'', there is probably no penny and1139nothing dropping (this idiom means that someone understood something1140after a period of confusion). Formal languages1141mean exactly what they say.11421143\end{description}11441145Because we all grow up speaking natural languages, it is sometimes1146hard to adjust to formal languages. The difference between formal and1147natural language is like the difference between poetry and prose, but1148more so: \index{poetry} \index{prose}11491150\begin{description}11511152\item[Poetry:] Words are used for their sounds as well as for1153their meaning, and the whole poem together creates an effect or1154emotional response. Ambiguity is not only common but often1155deliberate.11561157\item[Prose:] The literal meaning of words is more important,1158and the structure contributes more meaning. Prose is more amenable to1159analysis than poetry but still often ambiguous.11601161\item[Programs:] The meaning of a computer program is unambiguous1162and literal, and can be understood entirely by analysis of the1163tokens and structure.11641165\end{description}11661167Formal languages are more dense1168than natural languages, so it takes longer to read them. Also, the1169structure is important, so it is not always best to read1170from top to bottom, left to right. Instead, learn to parse the1171program in your head, identifying the tokens and interpreting the1172structure. Finally, the details matter. Small errors in1173spelling and punctuation, which you can get away1174with in natural languages, can make a big difference in a formal1175language.117611771178\section{Debugging}1179\index{debugging}11801181Programmers make mistakes. For whimsical reasons, programming errors1182are called {\bf bugs} and the process of tracking them down is called1183{\bf debugging}.1184\index{debugging}1185\index{bug}11861187Programming, and especially debugging, sometimes brings out strong1188emotions. If you are struggling with a difficult bug, you might1189feel angry, despondent, or embarrassed.11901191There is evidence that people naturally respond to computers as if1192they were people. When they work well, we think1193of them as teammates, and when they are obstinate or rude, we1194respond to them the same way we respond to rude,1195obstinate people (Reeves and Nass, {\it The Media1196Equation: How People Treat Computers, Television, and New Media1197Like Real People and Places}).1198\index{debugging!emotional response}1199\index{emotional debugging}12001201Preparing for these reactions might help you deal with them.1202One approach is to think of the computer as an employee with1203certain strengths, like speed and precision, and1204particular weaknesses, like lack of empathy and inability1205to grasp the big picture.12061207Your job is to be a good manager: find ways to take advantage1208of the strengths and mitigate the weaknesses. And find ways1209to use your emotions to engage with the problem,1210without letting your reactions interfere with your ability1211to work effectively.12121213Learning to debug can be frustrating, but it is a valuable skill1214that is useful for many activities beyond programming. At the1215end of each chapter there is a section, like this one,1216with my suggestions for debugging. I hope they help!121712181219\section{Glossary}12201221\begin{description}12221223\item[problem solving:] The process of formulating a problem, finding1224a solution, and expressing it.1225\index{problem solving}12261227\item[high-level language:] A programming language like Python that1228is designed to be easy for humans to read and write.1229\index{high-level language}12301231\item[low-level language:] A programming language that is designed1232to be easy for a computer to run; also called ``machine language'' or1233``assembly language''.1234\index{low-level language}12351236\item[portability:] A property of a program that can run on more1237than one kind of computer.1238\index{portability}12391240\item[interpreter:] A program that reads another program and executes1241it1242\index{interpret}12431244\item[prompt:] Characters displayed by the interpreter to indicate1245that it is ready to take input from the user.1246\index{prompt}12471248\item[program:] A set of instructions that specifies a computation.1249\index{program}12501251\item[print statement:] An instruction that causes the Python1252interpreter to display a value on the screen.1253\index{print statement}1254\index{statement!print}12551256\item[operator:] A special symbol that represents a simple computation like1257addition, multiplication, or string concatenation.1258\index{operator}12591260\item[value:] One of the basic units of data, like a number or string,1261that a program manipulates.1262\index{value}12631264\item[type:] A category of values. The types we have seen so far1265are integers (type {\tt int}), floating-point numbers (type {\tt1266float}), and strings (type {\tt str}).1267\index{type}12681269\item[integer:] A type that represents whole numbers.1270\index{integer}12711272\item[floating-point:] A type that represents numbers with fractional1273parts.1274\index{floating-point}12751276\item[string:] A type that represents sequences of characters.1277\index{string}12781279\item[natural language:] Any one of the languages that people speak that1280evolved naturally.1281\index{natural language}12821283\item[formal language:] Any one of the languages that people have designed1284for specific purposes, such as representing mathematical ideas or1285computer programs; all programming languages are formal languages.1286\index{formal language}12871288\item[token:] One of the basic elements of the syntactic structure of1289a program, analogous to a word in a natural language.1290\index{token}12911292\item[syntax:] The rules that govern the structure of a program.1293\index{syntax}12941295\item[parse:] To examine a program and analyze the syntactic structure.1296\index{parse}12971298\item[bug:] An error in a program.1299\index{bug}13001301\item[debugging:] The process of finding and correcting bugs.1302\index{debugging}13031304\end{description}130513061307\section{Exercises}13081309\begin{exercise}13101311It is a good idea to read this book in front of a computer so you can1312try out the examples as you go.13131314Whenever you are experimenting with a new feature, you should try1315to make mistakes. For example, in the ``Hello, world!'' program,1316what happens if you leave out one of the quotation marks? What1317if you leave out both? What if you spell {\tt print} wrong?1318\index{error message}13191320This kind of experiment helps you remember what you read; it also1321helps when you are programming, because you get to know what the error1322messages mean. It is better to make mistakes now and on purpose than1323later and accidentally.13241325\begin{enumerate}13261327\item In a print statement, what happens if you leave out one1328of the parentheses, or both?13291330\item If you are trying to print a string, what happens if you1331leave out one of the quotation marks, or both?13321333\item You can use a minus sign to make a negative number like1334{\tt -2}. What happens if you put a plus sign before a number?1335What about {\tt 2++2}?13361337\item In math notation, leading zeros are ok, as in {\tt 09}.1338What happens if you try this in Python? What about {\tt 011}?13391340\item What happens if you have two values with no operator1341between them?13421343\end{enumerate}13441345\end{exercise}1346134713481349\begin{exercise}13501351Start the Python interpreter and use it as a calculator.13521353\begin{enumerate}13541355\item How many seconds are there in 42 minutes 42 seconds?13561357\item How many miles are there in 10 kilometers? Hint: there are 1.611358kilometers in a mile.13591360\item If you run a 10 kilometer race in 42 minutes 42 seconds, what is1361your average pace (time per mile in minutes and seconds)? What is1362your average speed in miles per hour?13631364\index{calculator}1365\index{running pace}13661367\end{enumerate}13681369\end{exercise}13701371137213731374\chapter{Variables, expressions and statements}13751376One of the most powerful features of a programming language is the1377ability to manipulate {\bf variables}. A variable is a name that1378refers to a value.1379\index{variable}138013811382\section{Assignment statements}1383\label{variables}1384\index{assignment statement}1385\index{statement!assignment}13861387An {\bf assignment statement} creates a new variable and gives1388it a value:13891390\begin{verbatim}1391>>> message = 'And now for something completely different'1392>>> n = 171393>>> pi = 3.14159265358979321394\end{verbatim}1395%1396This example makes three assignments. The first assigns a string1397to a new variable named {\tt message};1398the second gives the integer {\tt 17} to {\tt n}; the third1399assigns the (approximate) value of $\pi$ to {\tt pi}.1400\index{state diagram}1401\index{diagram!state}14021403A common way to represent variables on paper is to write the name with1404an arrow pointing to its value. This kind of figure is1405called a {\bf state diagram} because it shows what state each of the1406variables is in (think of it as the variable's state of mind).1407Figure~\ref{fig.state2} shows the result of the previous example.14081409\begin{figure}1410\centerline1411{\includegraphics[scale=0.8]{figs/state2.pdf}}1412\caption{State diagram.}1413\label{fig.state2}1414\end{figure}1415141614171418\section{Variable names}1419\index{variable}14201421Programmers generally choose names for their variables that1422are meaningful---they document what the variable is used for.14231424Variable names can be as long as you like. They can contain1425both letters and numbers, but they can't begin with a number.1426It is legal to use uppercase letters, but it is conventional1427to use only lower case for variables names.14281429The underscore character, \verb"_", can appear in a name.1430It is often used in names with multiple words, such as1431\verb"your_name" or \verb"airspeed_of_unladen_swallow".1432\index{underscore character}14331434If you give a variable an illegal name, you get a syntax error:14351436\begin{verbatim}1437>>> 76trombones = 'big parade'1438SyntaxError: invalid syntax1439>>> more@ = 10000001440SyntaxError: invalid syntax1441>>> class = 'Advanced Theoretical Zymurgy'1442SyntaxError: invalid syntax1443\end{verbatim}1444%1445{\tt 76trombones} is illegal because it begins with a number.1446{\tt more@} is illegal because it contains an illegal character, {\tt1447@}. But what's wrong with {\tt class}?14481449It turns out that {\tt class} is one of Python's {\bf keywords}. The1450interpreter uses keywords to recognize the structure of the program,1451and they cannot be used as variable names.1452\index{keyword}14531454Python 3 has these keywords:14551456\begin{verbatim}1457False class finally is return1458None continue for lambda try1459True def from nonlocal while1460and del global not with1461as elif if or yield1462assert else import pass1463break except in raise1464\end{verbatim}1465%1466You don't have to memorize this list. In most development environments,1467keywords are displayed in a different color; if you try to use one1468as a variable name, you'll know.146914701471\section{Expressions and statements}14721473An {\bf expression} is a combination of values, variables, and operators.1474A value all by itself is considered an expression, and so is1475a variable, so the following are all legal expressions:1476\index{expression}14771478\begin{verbatim}1479>>> 421480421481>>> n1482171483>>> n + 251484421485\end{verbatim}1486%1487When you type an expression at the prompt, the interpreter1488{\bf evaluates} it, which means that it finds the value of1489the expression.1490In this example, {\tt n} has the value 17 and1491{\tt n + 25} has the value 42.1492\index{evaluate}14931494A {\bf statement} is a unit of code that has an effect, like1495creating a variable or displaying a value.1496\index{statement}14971498\begin{verbatim}1499>>> n = 171500>>> print(n)1501\end{verbatim}1502%1503The first line is an assignment statement that gives a value to1504{\tt n}. The second line is a print statement that displays the1505value of {\tt n}.15061507When you type a statement, the interpreter {\bf executes} it,1508which means that it does whatever the statement says. In general,1509statements don't have values.1510\index{execute}151115121513\section{Script mode}15141515So far we have run Python in {\bf interactive mode}, which1516means that you interact directly with the interpreter.1517Interactive mode is a good way to get started,1518but if you are working with more than a few lines of code, it can be1519clumsy.1520\index{interactive mode}15211522The alternative is to save code in a file called a {\bf script} and1523then run the interpreter in {\bf script mode} to execute the script. By1524convention, Python scripts have names that end with {\tt .py}.1525\index{script}1526\index{script mode}15271528If you know how to create and run a script on your computer, you1529are ready to go. Otherwise I recommend using PythonAnywhere again.1530I have posted instructions for running in script mode at1531\url{http://tinyurl.com/thinkpython2e}.15321533Because Python provides both modes,1534you can test bits of code in interactive mode before you put them1535in a script. But there are differences between interactive mode1536and script mode that can be confusing.1537\index{interactive mode}1538\index{script mode}15391540For example, if you are using Python as a calculator, you might type15411542\begin{verbatim}1543>>> miles = 26.21544>>> miles * 1.61154542.1821546\end{verbatim}15471548The first line assigns a value to {\tt miles}, but it has no visible1549effect. The second line is an expression, so the1550interpreter evaluates it and displays the result. It turns out that a1551marathon is about 42 kilometers.15521553But if you type the same code into a script and run it, you get no1554output at all.1555In script mode an expression, all by itself, has no1556visible effect. Python evaluates the expression, but it doesn't1557display the result.1558To display the result, you need a {\tt print} statement like this:15591560\begin{verbatim}1561miles = 26.21562print(miles * 1.61)1563\end{verbatim}15641565This behavior can be confusing at first.1566To check your understanding, type the following statements in the1567Python interpreter and see what they do:15681569\begin{verbatim}157051571x = 51572x + 11573\end{verbatim}15741575Now put the same statements in a script and run it. What1576is the output? Modify the script by transforming each1577expression into a print statement and then run it again.157815791580\section{Order of operations}1581\index{order of operations}1582\index{PEMDAS}15831584When an expression contains more than one operator, the order of1585evaluation depends on the {\bf order of operations}. For1586mathematical operators, Python follows mathematical convention.1587The acronym {\bf PEMDAS} is a useful way to1588remember the rules:15891590\begin{itemize}15911592\item {\bf P}arentheses have the highest precedence and can be used1593to force an expression to evaluate in the order you want. Since1594expressions in parentheses are evaluated first, {\tt 2 * (3-1)} is 4,1595and {\tt (1+1)**(5-2)} is 8. You can also use parentheses to make an1596expression easier to read, as in {\tt (minute * 100) / 60}, even1597if it doesn't change the result.15981599\item {\bf E}xponentiation has the next highest precedence, so1600{\tt 1 + 2**3} is 9, not 27, and {\tt 2 * 3**2} is 18, not 36.16011602\item {\bf M}ultiplication and {\bf D}ivision have higher precedence1603than {\bf A}ddition and {\bf S}ubtraction. So {\tt 2*3-1} is 5, not16044, and {\tt 6+4/2} is 8, not 5.16051606\item Operators with the same precedence are evaluated from left to1607right (except exponentiation). So in the expression {\tt degrees /16082 * pi}, the division happens first and the result is multiplied1609by {\tt pi}. To divide by $2 \pi$, you can use parentheses or write1610{\tt degrees / 2 / pi}.16111612\end{itemize}16131614I don't work very hard to remember the precedence of1615operators. If I can't tell by looking at the expression, I use1616parentheses to make it obvious.161716181619\section{String operations}1620\index{string!operation}1621\index{operator!string}16221623In general, you can't perform mathematical operations on strings, even1624if the strings look like numbers, so the following are illegal:16251626\begin{verbatim}1627'chinese'-'food' 'eggs'/'easy' 'third'*'a charm'1628\end{verbatim}1629%1630But there are two exceptions, {\tt +} and {\tt *}.16311632The {\tt +} operator performs {\bf string concatenation}, which means1633it joins the strings by linking them end-to-end. For example:1634\index{concatenation}16351636\begin{verbatim}1637>>> first = 'throat'1638>>> second = 'warbler'1639>>> first + second1640throatwarbler1641\end{verbatim}1642%1643The {\tt *} operator also works on strings; it performs repetition.1644For example, \verb"'Spam'*3" is \verb"'SpamSpamSpam'". If one of the1645values is a string, the other has to be an integer.16461647This use of {\tt +} and {\tt *} makes sense by1648analogy with addition and multiplication. Just as {\tt 4*3} is1649equivalent to {\tt 4+4+4}, we expect \verb"'Spam'*3" to be the same as1650\verb"'Spam'+'Spam'+'Spam'", and it is. On the other hand, there is a1651significant way in which string concatenation and repetition are1652different from integer addition and multiplication.1653Can you think of a property that addition has1654that string concatenation does not?1655\index{commutativity}165616571658\section{Comments}1659\index{comment}16601661As programs get bigger and more complicated, they get more difficult1662to read. Formal languages are dense, and it is often difficult to1663look at a piece of code and figure out what it is doing, or why.16641665For this reason, it is a good idea to add notes to your programs to explain1666in natural language what the program is doing. These notes are called1667{\bf comments}, and they start with the \verb"#" symbol:16681669\begin{verbatim}1670# compute the percentage of the hour that has elapsed1671percentage = (minute * 100) / 601672\end{verbatim}1673%1674In this case, the comment appears on a line by itself. You can also put1675comments at the end of a line:16761677\begin{verbatim}1678percentage = (minute * 100) / 60 # percentage of an hour1679\end{verbatim}1680%1681Everything from the {\tt \#} to the end of the line is ignored---it1682has no effect on the execution of the program.16831684Comments are most useful when they document non-obvious features of1685the code. It is reasonable to assume that the reader can figure out1686{\em what} the code does; it is more useful to explain {\em why}.16871688This comment is redundant with the code and useless:16891690\begin{verbatim}1691v = 5 # assign 5 to v1692\end{verbatim}1693%1694This comment contains useful information that is not in the code:16951696\begin{verbatim}1697v = 5 # velocity in meters/second.1698\end{verbatim}1699%1700Good variable names can reduce the need for comments, but1701long names can make complex expressions hard to read, so there is1702a tradeoff.170317041705\section{Debugging}1706\index{debugging}1707\index{bug}17081709Three kinds of errors can occur in a program: syntax errors, runtime1710errors, and semantic errors. It is useful1711to distinguish between them in order to track them down more quickly.17121713\begin{description}17141715\item[Syntax error:] ``Syntax'' refers to the structure of a program1716and the rules about that structure. For example, parentheses have1717to come in matching pairs, so {\tt (1 + 2)} is legal, but {\tt 8)}1718is a {\bf syntax error}. \index{syntax error} \index{error!syntax}1719\index{error message}1720\index{syntax}17211722If there is a syntax error1723anywhere in your program, Python displays an error message and quits,1724and you will not be able to run the program. During the first few1725weeks of your programming career, you might spend a lot of1726time tracking down syntax errors. As you gain experience, you will1727make fewer errors and find them faster.172817291730\item[Runtime error:] The second type of error is a runtime error, so1731called because the error does not appear until after the program has1732started running. These errors are also called {\bf exceptions}1733because they usually indicate that something exceptional (and bad)1734has happened. \index{runtime error} \index{error!runtime}1735\index{exception} \index{safe language} \index{language!safe}17361737Runtime errors are rare in the simple programs you will see in the1738first few chapters, so it might be a while before you encounter one.173917401741\item[Semantic error:] The third type of error is ``semantic'', which1742means related to meaning. If there is a semantic error in your1743program, it will run without generating error messages, but it will1744not do the right thing. It will do something else. Specifically,1745it will do what you told it to do. \index{semantic error}1746\index{error!semantic} \index{error message}17471748Identifying semantic errors can be tricky because it requires you to work1749backward by looking at the output of the program and trying to figure1750out what it is doing.17511752\end{description}175317541755\section{Glossary}17561757\begin{description}17581759\item[variable:] A name that refers to a value.1760\index{variable}17611762\item[assignment:] A statement that assigns a value to a variable.1763\index{assignment}17641765\item[state diagram:] A graphical representation of a set of variables and the1766values they refer to.1767\index{state diagram}17681769\item[keyword:] A reserved word that is used to parse a1770program; you cannot use keywords like {\tt if}, {\tt def}, and {\tt while} as1771variable names.1772\index{keyword}17731774\item[operand:] One of the values on which an operator operates.1775\index{operand}17761777\item[expression:] A combination of variables, operators, and values that1778represents a single result.1779\index{expression}17801781\item[evaluate:] To simplify an expression by performing the operations1782in order to yield a single value.17831784\item[statement:] A section of code that represents a command or action. So1785far, the statements we have seen are assignments and print statements.1786\index{statement}17871788\item[execute:] To run a statement and do what it says.1789\index{execute}17901791\item[interactive mode:] A way of using the Python interpreter by1792typing code at the prompt.1793\index{interactive mode}17941795\item[script mode:] A way of using the Python interpreter to read1796code from a script and run it.1797\index{script mode}17981799\item[script:] A program stored in a file.1800\index{script}18011802\item[order of operations:] Rules governing the order in which1803expressions involving multiple operators and operands are evaluated.1804\index{order of operations}18051806\item[concatenate:] To join two operands end-to-end.1807\index{concatenation}18081809\item[comment:] Information in a program that is meant for other1810programmers (or anyone reading the source code) and has no effect on the1811execution of the program.1812\index{comment}18131814\item[syntax error:] An error in a program that makes it impossible1815to parse (and therefore impossible to interpret).1816\index{syntax error}18171818\item[exception:] An error that is detected while the program is running.1819\index{exception}18201821\item[semantics:] The meaning of a program.1822\index{semantics}18231824\item[semantic error:] An error in a program that makes it do something1825other than what the programmer intended.1826\index{semantic error}18271828\end{description}182918301831\section{Exercises}18321833\begin{exercise}18341835Repeating my advice from the previous chapter, whenever you learn1836a new feature, you should try it out in interactive mode and make1837errors on purpose to see what goes wrong.18381839\begin{itemize}18401841\item We've seen that {\tt n = 42} is legal. What about {\tt 42 = n}?18421843\item How about {\tt x = y = 1}?18441845\item In some languages every statement ends with a semi-colon, {\tt ;}.1846What happens if you put a semi-colon at the end of a Python statement?18471848\item What if you put a period at the end of a statement?18491850\item In math notation you can multiply $x$ and $y$ like this: $x y$.1851What happens if you try that in Python?18521853\end{itemize}18541855\end{exercise}185618571858\begin{exercise}18591860Practice using the Python interpreter as a calculator:1861\index{calculator}18621863\begin{enumerate}18641865\item The volume of a sphere with radius $r$ is $\frac{4}{3} \pi r^3$.1866What is the volume of a sphere with radius 5?18671868\item Suppose the cover price of a book is \$24.95, but bookstores get a186940\% discount. Shipping costs \$3 for the first copy and 75 cents1870for each additional copy. What is the total wholesale cost for187160 copies?18721873\item If I leave my house at 6:52 am and run 1 mile at an easy pace1874(8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at1875easy pace again, what time do I get home for breakfast?1876\index{running pace}18771878\end{enumerate}1879\end{exercise}188018811882\chapter{Functions}1883\label{funcchap}18841885In the context of programming, a {\bf function} is a named sequence of1886statements that performs a computation. When you define a function,1887you specify the name and the sequence of statements. Later, you can1888``call'' the function by name.1889\index{function}18901891\section{Function calls}1892\label{functionchap}1893\index{function call}18941895We have already seen one example of a {\bf function call}:18961897\begin{verbatim}1898>>> type(42)1899<class 'int'>1900\end{verbatim}1901%1902The name of the function is {\tt type}. The expression in parentheses1903is called the {\bf argument} of the function. The result, for this1904function, is the type of the argument.1905\index{parentheses!argument in}19061907It is common to say that a function ``takes'' an argument and ``returns''1908a result. The result is also called the {\bf return value}.1909\index{argument}1910\index{return value}19111912Python provides functions that convert values1913from one type to another. The {\tt int} function takes any value and1914converts it to an integer, if it can, or complains otherwise:1915\index{conversion!type}1916\index{type conversion}1917\index{int function}1918\index{function!int}19191920\begin{verbatim}1921>>> int('32')1922321923>>> int('Hello')1924ValueError: invalid literal for int(): Hello1925\end{verbatim}1926%1927{\tt int} can convert floating-point values to integers, but it1928doesn't round off; it chops off the fraction part:19291930\begin{verbatim}1931>>> int(3.99999)193231933>>> int(-2.3)1934-21935\end{verbatim}1936%1937{\tt float} converts integers and strings to floating-point1938numbers:1939\index{float function}1940\index{function!float}19411942\begin{verbatim}1943>>> float(32)194432.01945>>> float('3.14159')19463.141591947\end{verbatim}1948%1949Finally, {\tt str} converts its argument to a string:1950\index{str function}1951\index{function!str}19521953\begin{verbatim}1954>>> str(32)1955'32'1956>>> str(3.14159)1957'3.14159'1958\end{verbatim}1959%19601961\section{Math functions}1962\index{math function}1963\index{function!math}19641965Python has a math module that provides most of the familiar1966mathematical functions. A {\bf module} is a file that contains a1967collection of related functions.1968\index{module}1969\index{module object}19701971Before we can use the functions in a module, we have to import it with1972an {\bf import statement}:19731974\begin{verbatim}1975>>> import math1976\end{verbatim}1977%1978This statement creates a {\bf module object} named math. If1979you display the module object, you get some information about it:19801981\begin{verbatim}1982>>> math1983<module 'math' (built-in)>1984\end{verbatim}1985%1986The module object contains the functions and variables defined in the1987module. To access one of the functions, you have to specify the name1988of the module and the name of the function, separated by a dot (also1989known as a period). This format is called {\bf dot notation}.1990\index{dot notation}19911992\begin{verbatim}1993>>> ratio = signal_power / noise_power1994>>> decibels = 10 * math.log10(ratio)19951996>>> radians = 0.71997>>> height = math.sin(radians)1998\end{verbatim}1999%2000The first example uses \verb"math.log10" to compute2001a signal-to-noise ratio in decibels (assuming that \verb"signal_power" and2002\verb"noise_power" are defined). The math module also provides {\tt log},2003which computes logarithms base {\tt e}.2004\index{log function}2005\index{function!log}2006\index{sine function}2007\index{radian}2008\index{trigonometric function}2009\index{function!trigonometric}20102011The second example finds the sine of {\tt radians}. The variable name {\tt radians} is a hint that {\tt sin} and the other trigonometric2012functions ({\tt cos}, {\tt tan}, etc.) take arguments in radians. To2013convert from degrees to radians, divide by 180 and multiply by2014$\pi$:20152016\begin{verbatim}2017>>> degrees = 452018>>> radians = degrees / 180.0 * math.pi2019>>> math.sin(radians)20200.7071067811872021\end{verbatim}2022%2023The expression {\tt math.pi} gets the variable {\tt pi} from the math2024module. Its value is a floating-point approximation2025of $\pi$, accurate to about 15 digits.2026\index{pi}20272028If you know2029trigonometry, you can check the previous result by comparing it to2030the square root of two, divided by two:2031\index{sqrt function}2032\index{function!sqrt}20332034\begin{verbatim}2035>>> math.sqrt(2) / 2.020360.7071067811872037\end{verbatim}2038%20392040\section{Composition}2041\index{composition}20422043So far, we have looked at the elements of a program---variables,2044expressions, and statements---in isolation, without talking about how to2045combine them.20462047One of the most useful features of programming languages is their2048ability to take small building blocks and {\bf compose} them. For2049example, the argument of a function can be any kind of expression,2050including arithmetic operators:20512052\begin{verbatim}2053x = math.sin(degrees / 360.0 * 2 * math.pi)2054\end{verbatim}2055%2056And even function calls:20572058\begin{verbatim}2059x = math.exp(math.log(x+1))2060\end{verbatim}2061%2062Almost anywhere you can put a value, you can put an arbitrary2063expression, with one exception: the left side of an assignment2064statement has to be a variable name. Any other expression on the left2065side is a syntax error (we will see exceptions to this rule2066later).20672068\begin{verbatim}2069>>> minutes = hours * 60 # right2070>>> hours * 60 = minutes # wrong!2071SyntaxError: can't assign to operator2072\end{verbatim}2073%2074\index{SyntaxError}2075\index{exception!SyntaxError}207620772078\section{Adding new functions}20792080So far, we have only been using the functions that come with Python,2081but it is also possible to add new functions.2082A {\bf function definition} specifies the name of a new function and2083the sequence of statements that run when the function is called.2084\index{function}2085\index{function definition}2086\index{definition!function}20872088Here is an example:20892090\begin{verbatim}2091def print_lyrics():2092print("I'm a lumberjack, and I'm okay.")2093print("I sleep all night and I work all day.")2094\end{verbatim}2095%2096{\tt def} is a keyword that indicates that this is a function2097definition. The name of the function is \verb"print_lyrics". The2098rules for function names are the same as for variable names: letters,2099numbers and underscore are legal, but the first character2100can't be a number. You can't use a keyword as the name of a function,2101and you should avoid having a variable and a function with the same2102name.2103\index{def keyword}2104\index{keyword!def}2105\index{argument}21062107The empty parentheses after the name indicate that this function2108doesn't take any arguments.2109\index{parentheses!empty}2110\index{header}2111\index{body}2112\index{indentation}2113\index{colon}21142115The first line of the function definition is called the {\bf header};2116the rest is called the {\bf body}. The header has to end with a colon2117and the body has to be indented. By convention, indentation is2118always four spaces. The body can contain2119any number of statements.21202121The strings in the print statements are enclosed in double2122quotes. Single quotes and double quotes do the same thing;2123most people use single quotes except in cases like this where2124a single quote (which is also an apostrophe) appears in the string.21252126All quotation marks (single and double)2127must be ``straight quotes'', usually2128located next to Enter on the keyboard. ``Curly quotes'', like2129the ones in this sentence, are not legal in Python.21302131If you type a function definition in interactive mode, the interpreter2132prints dots ({\tt ...}) to let you know that the definition2133isn't complete:2134\index{ellipses}21352136\begin{verbatim}2137>>> def print_lyrics():2138... print("I'm a lumberjack, and I'm okay.")2139... print("I sleep all night and I work all day.")2140...2141\end{verbatim}2142%2143To end the function, you have to enter an empty line.21442145Defining a function creates a {\bf function object}, which2146has type \verb"function":2147\index{function type}2148\index{type!function}21492150\begin{verbatim}2151>>> print(print_lyrics)2152<function print_lyrics at 0xb7e99e9c>2153>>> type(print_lyrics)2154<class 'function'>2155\end{verbatim}2156%2157The syntax for calling the new function is the same as2158for built-in functions:21592160\begin{verbatim}2161>>> print_lyrics()2162I'm a lumberjack, and I'm okay.2163I sleep all night and I work all day.2164\end{verbatim}2165%2166Once you have defined a function, you can use it inside another2167function. For example, to repeat the previous refrain, we could write2168a function called \verb"repeat_lyrics":21692170\begin{verbatim}2171def repeat_lyrics():2172print_lyrics()2173print_lyrics()2174\end{verbatim}2175%2176And then call \verb"repeat_lyrics":21772178\begin{verbatim}2179>>> repeat_lyrics()2180I'm a lumberjack, and I'm okay.2181I sleep all night and I work all day.2182I'm a lumberjack, and I'm okay.2183I sleep all night and I work all day.2184\end{verbatim}2185%2186But that's not really how the song goes.218721882189\section{Definitions and uses}2190\index{function definition}21912192Pulling together the code fragments from the previous section, the2193whole program looks like this:21942195\begin{verbatim}2196def print_lyrics():2197print("I'm a lumberjack, and I'm okay.")2198print("I sleep all night and I work all day.")21992200def repeat_lyrics():2201print_lyrics()2202print_lyrics()22032204repeat_lyrics()2205\end{verbatim}2206%2207This program contains two function definitions: \verb"print_lyrics" and2208\verb"repeat_lyrics". Function definitions get executed just like other2209statements, but the effect is to create function objects. The statements2210inside the function do not run until the function is called, and2211the function definition generates no output.2212\index{use before def}22132214As you might expect, you have to create a function before you can2215run it. In other words, the function definition has to run2216before the function gets called.22172218As an exercise, move the last line of this program2219to the top, so the function call appears before the definitions. Run2220the program and see what error2221message you get.22222223Now move the function call back to the bottom2224and move the definition of \verb"print_lyrics" after the definition of2225\verb"repeat_lyrics". What happens when you run this program?222622272228\section{Flow of execution}2229\index{flow of execution}22302231To ensure that a function is defined before its first use,2232you have to know the order statements run in, which is2233called the {\bf flow of execution}.22342235Execution always begins at the first statement of the program.2236Statements are run one at a time, in order from top to bottom.22372238Function definitions do not alter the flow of execution of the2239program, but remember that statements inside the function don't2240run until the function is called.22412242A function call is like a detour in the flow of execution. Instead of2243going to the next statement, the flow jumps to the body of2244the function, runs the statements there, and then comes back2245to pick up where it left off.22462247That sounds simple enough, until you remember that one function can2248call another. While in the middle of one function, the program might2249have to run the statements in another function. Then, while2250running that new function, the program might have to run yet2251another function!22522253Fortunately, Python is good at keeping track of where it is, so each2254time a function completes, the program picks up where it left off in2255the function that called it. When it gets to the end of the program,2256it terminates.22572258In summary, when you read a program, you2259don't always want to read from top to bottom. Sometimes it makes2260more sense if you follow the flow of execution.226122622263\section{Parameters and arguments}2264\label{parameters}2265\index{parameter}2266\index{function parameter}2267\index{argument}2268\index{function argument}22692270Some of the functions we have seen require arguments. For2271example, when you call {\tt math.sin} you pass a number2272as an argument. Some functions take more than one argument:2273{\tt math.pow} takes two, the base and the exponent.22742275Inside the function, the arguments are assigned to2276variables called {\bf parameters}. Here is a definition for2277a function that takes an argument:2278\index{parentheses!parameters in}22792280\begin{verbatim}2281def print_twice(bruce):2282print(bruce)2283print(bruce)2284\end{verbatim}2285%2286This function assigns the argument to a parameter2287named {\tt bruce}. When the function is called, it prints the value of2288the parameter (whatever it is) twice.22892290This function works with any value that can be printed.22912292\begin{verbatim}2293>>> print_twice('Spam')2294Spam2295Spam2296>>> print_twice(42)2297422298422299>>> print_twice(math.pi)23003.1415926535923013.141592653592302\end{verbatim}2303%2304The same rules of composition that apply to built-in functions also2305apply to programmer-defined functions, so we can use any kind of expression2306as an argument for \verb"print_twice":2307\index{composition}2308\index{programmer-defined function}2309\index{function!programmer defined}23102311\begin{verbatim}2312>>> print_twice('Spam '*4)2313Spam Spam Spam Spam2314Spam Spam Spam Spam2315>>> print_twice(math.cos(math.pi))2316-1.02317-1.02318\end{verbatim}2319%2320The argument is evaluated before the function is called, so2321in the examples the expressions \verb"'Spam '*4" and2322{\tt math.cos(math.pi)} are only evaluated once.2323\index{argument}23242325You can also use a variable as an argument:23262327\begin{verbatim}2328>>> michael = 'Eric, the half a bee.'2329>>> print_twice(michael)2330Eric, the half a bee.2331Eric, the half a bee.2332\end{verbatim}2333%2334The name of the variable we pass as an argument ({\tt michael}) has2335nothing to do with the name of the parameter ({\tt bruce}). It2336doesn't matter what the value was called back home (in the caller);2337here in \verb"print_twice", we call everybody {\tt bruce}.233823392340\section{Variables and parameters are local}2341\index{local variable}2342\index{variable!local}23432344When you create a variable inside a function, it is {\bf local},2345which means that it only2346exists inside the function. For example:2347\index{parentheses!parameters in}23482349\begin{verbatim}2350def cat_twice(part1, part2):2351cat = part1 + part22352print_twice(cat)2353\end{verbatim}2354%2355This function takes two arguments, concatenates them, and prints2356the result twice. Here is an example that uses it:2357\index{concatenation}23582359\begin{verbatim}2360>>> line1 = 'Bing tiddle '2361>>> line2 = 'tiddle bang.'2362>>> cat_twice(line1, line2)2363Bing tiddle tiddle bang.2364Bing tiddle tiddle bang.2365\end{verbatim}2366%2367When \verb"cat_twice" terminates, the variable {\tt cat}2368is destroyed. If we try to print it, we get an exception:2369\index{NameError}2370\index{exception!NameError}23712372\begin{verbatim}2373>>> print(cat)2374NameError: name 'cat' is not defined2375\end{verbatim}2376%2377Parameters are also local.2378For example, outside \verb"print_twice", there is no2379such thing as {\tt bruce}.2380\index{parameter}238123822383\section{Stack diagrams}2384\label{stackdiagram}2385\index{stack diagram}2386\index{function frame}2387\index{frame}23882389To keep track of which variables can be used where, it is sometimes2390useful to draw a {\bf stack diagram}. Like state diagrams, stack2391diagrams show the value of each variable, but they also show the2392function each variable belongs to.2393\index{stack diagram}2394\index{diagram!stack}23952396Each function is represented by a {\bf frame}. A frame is a box with2397the name of a function beside it and the parameters and variables of2398the function inside it. The stack diagram for the previous example is2399shown in Figure~\ref{fig.stack}.24002401\begin{figure}2402\centerline2403{\includegraphics[scale=0.8]{figs/stack.pdf}}2404\caption{Stack diagram.}2405\label{fig.stack}2406\end{figure}240724082409The frames are arranged in a stack that indicates which function2410called which, and so on. In this example, \verb"print_twice"2411was called by \verb"cat_twice", and \verb"cat_twice" was called by2412\verb"__main__", which is a special name for the topmost frame. When2413you create a variable outside of any function, it belongs to2414\verb"__main__".24152416\index{main}24172418Each parameter refers to the same value as its corresponding2419argument. So, {\tt part1} has the same value as2420{\tt line1}, {\tt part2} has the same value as {\tt line2},2421and {\tt bruce} has the same value as {\tt cat}.24222423If an error occurs during a function call, Python prints the2424name of the function, the name of the function that called2425it, and the name of the function that called {\em that}, all the2426way back to \verb"__main__".24272428For example, if you try to access {\tt cat} from within2429\verb"print_twice", you get a {\tt NameError}:24302431\begin{verbatim}2432Traceback (innermost last):2433File "test.py", line 13, in __main__2434cat_twice(line1, line2)2435File "test.py", line 5, in cat_twice2436print_twice(cat)2437File "test.py", line 9, in print_twice2438print(cat)2439NameError: name 'cat' is not defined2440\end{verbatim}2441%2442This list of functions is called a {\bf traceback}. It tells you what2443program file the error occurred in, and what line, and what functions2444were executing at the time. It also shows the line of code that2445caused the error.2446\index{traceback}24472448The order of the functions in the traceback is the same as the2449order of the frames in the stack diagram. The function that is2450currently running is at the bottom.245124522453\section{Fruitful functions and void functions}2454\index{fruitful function}2455\index{void function}2456\index{function!fruitful}2457\index{function!void}24582459Some of the functions we have used, such as the math functions, return2460results; for lack of a better name, I call them {\bf fruitful2461functions}. Other functions, like \verb"print_twice", perform an2462action but don't return a value. They are called {\bf void2463functions}.24642465When you call a fruitful function, you almost always2466want to do something with the result; for example, you might2467assign it to a variable or use it as part of an expression:24682469\begin{verbatim}2470x = math.cos(radians)2471golden = (math.sqrt(5) + 1) / 22472\end{verbatim}2473%2474When you call a function in interactive mode, Python displays2475the result:24762477\begin{verbatim}2478>>> math.sqrt(5)24792.23606797749978982480\end{verbatim}2481%2482But in a script, if you call a fruitful function all by itself,2483the return value is lost forever!24842485\begin{verbatim}2486math.sqrt(5)2487\end{verbatim}2488%2489This script computes the square root of 5, but since it doesn't store2490or display the result, it is not very useful.2491\index{interactive mode}2492\index{script mode}24932494Void functions might display something on the screen or have some2495other effect, but they don't have a return value. If you2496assign the result to a variable, you get a special value called2497{\tt None}.2498\index{None special value}2499\index{special value!None}25002501\begin{verbatim}2502>>> result = print_twice('Bing')2503Bing2504Bing2505>>> print(result)2506None2507\end{verbatim}2508%2509The value {\tt None} is not the same as the string \verb"'None'".2510It is a special value that has its own type:25112512\begin{verbatim}2513>>> type(None)2514<class 'NoneType'>2515\end{verbatim}2516%2517The functions we have written so far are all void. We will start2518writing fruitful functions in a few chapters.2519\index{NoneType type}2520\index{type!NoneType}252125222523\section{Why functions?}2524\index{function!reasons for}25252526It may not be clear why it is worth the trouble to divide2527a program into functions. There are several reasons:25282529\begin{itemize}25302531\item Creating a new function gives you an opportunity to name a group2532of statements, which makes your program easier to read and debug.25332534\item Functions can make a program smaller by eliminating repetitive2535code. Later, if you make a change, you only have2536to make it in one place.25372538\item Dividing a long program into functions allows you to debug the2539parts one at a time and then assemble them into a working whole.25402541\item Well-designed functions are often useful for many programs.2542Once you write and debug one, you can reuse it.25432544\end{itemize}254525462547\section{Debugging}25482549One of the most important skills you will acquire is debugging.2550Although it can be frustrating, debugging is one of the most2551intellectually rich, challenging, and interesting parts of2552programming.2553\index{experimental debugging}2554\index{debugging!experimental}25552556In some ways debugging is like detective work. You are confronted2557with clues and you have to infer the processes and events that led2558to the results you see.25592560Debugging is also like an experimental science. Once you have an idea2561about what is going wrong, you modify your program and try again. If2562your hypothesis was correct, you can predict the result of the2563modification, and you take a step closer to a working program. If2564your hypothesis was wrong, you have to come up with a new one. As2565Sherlock Holmes pointed out, ``When you have eliminated the2566impossible, whatever remains, however improbable, must be the truth.''2567(A. Conan Doyle, {\em The Sign of Four})2568\index{Holmes, Sherlock}2569\index{Doyle, Arthur Conan}25702571For some people, programming and debugging are the same thing. That2572is, programming is the process of gradually debugging a program until2573it does what you want. The idea is that you should start with a2574working program and make small modifications,2575debugging them as you go.25762577For example, Linux is an operating system that contains millions of2578lines of code, but it started out as a simple program Linus Torvalds2579used to explore the Intel 80386 chip. According to Larry Greenfield,2580``One of Linus's earlier projects was a program that would switch2581between printing AAAA and BBBB. This later evolved to Linux.''2582({\em The Linux Users' Guide} Beta Version 1).2583\index{Linux}258425852586\section{Glossary}25872588\begin{description}25892590\item[function:] A named sequence of statements that performs some2591useful operation. Functions may or may not take arguments and may or2592may not produce a result.2593\index{function}25942595\item[function definition:] A statement that creates a new function,2596specifying its name, parameters, and the statements it contains.2597\index{function definition}25982599\item[function object:] A value created by a function definition.2600The name of the function is a variable that refers to a function2601object.2602\index{function definition}26032604\item[header:] The first line of a function definition.2605\index{header}26062607\item[body:] The sequence of statements inside a function definition.2608\index{body}26092610\item[parameter:] A name used inside a function to refer to the value2611passed as an argument.2612\index{parameter}26132614\item[function call:] A statement that runs a function. It2615consists of the function name followed by an argument list in2616parentheses.2617\index{function call}26182619\item[argument:] A value provided to a function when the function is called.2620This value is assigned to the corresponding parameter in the function.2621\index{argument}26222623\item[local variable:] A variable defined inside a function. A local2624variable can only be used inside its function.2625\index{local variable}26262627\item[return value:] The result of a function. If a function call2628is used as an expression, the return value is the value of2629the expression.2630\index{return value}26312632\item[fruitful function:] A function that returns a value.2633\index{fruitful function}26342635\item[void function:] A function that always returns {\tt None}.2636\index{void function}26372638\item[{\tt None}:] A special value returned by void functions.2639\index{None special value}2640\index{special value!None}26412642\item[module:] A file that contains a2643collection of related functions and other definitions.2644\index{module}26452646\item[import statement:] A statement that reads a module file and creates2647a module object.2648\index{import statement}2649\index{statement!import}26502651\item[module object:] A value created by an {\tt import} statement2652that provides access to the values defined in a module.2653\index{module}26542655\item[dot notation:] The syntax for calling a function in another2656module by specifying the module name followed by a dot (period) and2657the function name.2658\index{dot notation}26592660\item[composition:] Using an expression as part of a larger expression,2661or a statement as part of a larger statement.2662\index{composition}26632664\item[flow of execution:] The order statements run in.2665\index{flow of execution}26662667\item[stack diagram:] A graphical representation of a stack of functions,2668their variables, and the values they refer to.2669\index{stack diagram}26702671\item[frame:] A box in a stack diagram that represents a function call.2672It contains the local variables and parameters of the function.2673\index{function frame}2674\index{frame}26752676\item[traceback:] A list of the functions that are executing,2677printed when an exception occurs.2678\index{traceback}267926802681\end{description}268226832684\section{Exercises}26852686\begin{exercise}2687\index{len function}2688\index{function!len}26892690Write a function named \verb"right_justify" that takes a string2691named {\tt s} as a parameter and prints the string with enough2692leading spaces so that the last letter of the string is in column 702693of the display.26942695\begin{verbatim}2696>>> right_justify('monty')2697monty2698\end{verbatim}26992700Hint: Use string concatenation and repetition. Also,2701Python provides a built-in function called {\tt len} that2702returns the length of a string, so the value of \verb"len('monty')" is 5.27032704\end{exercise}270527062707\begin{exercise}2708\index{function object}2709\index{object!function}27102711A function object is a value you can assign to a variable2712or pass as an argument. For example, \verb"do_twice" is a function2713that takes a function object as an argument and calls it twice:27142715\begin{verbatim}2716def do_twice(f):2717f()2718f()2719\end{verbatim}27202721Here's an example that uses \verb"do_twice" to call a function2722named \verb"print_spam" twice.27232724\begin{verbatim}2725def print_spam():2726print('spam')27272728do_twice(print_spam)2729\end{verbatim}27302731\begin{enumerate}27322733\item Type this example into a script and test it.27342735\item Modify \verb"do_twice" so that it takes two arguments, a2736function object and a value, and calls the function twice,2737passing the value as an argument.27382739\item Copy the definition of2740\verb"print_twice" from earlier in this chapter to your script.27412742\item Use the modified version of \verb"do_twice" to call2743\verb"print_twice" twice, passing \verb"'spam'" as an argument.27442745\item Define a new function called2746\verb"do_four" that takes a function object and a value2747and calls the function four times, passing the value2748as a parameter. There should be only2749two statements in the body of this function, not four.27502751\end{enumerate}27522753Solution: \url{http://thinkpython2.com/code/do_four.py}.27542755\end{exercise}2756275727582759\begin{exercise}27602761Note: This exercise should be2762done using only the statements and other features we have learned so2763far.27642765\begin{enumerate}27662767\item Write a function that draws a grid like the following:2768\index{grid}27692770\begin{verbatim}2771+ - - - - + - - - - +2772| | |2773| | |2774| | |2775| | |2776+ - - - - + - - - - +2777| | |2778| | |2779| | |2780| | |2781+ - - - - + - - - - +2782\end{verbatim}2783%2784Hint: to print more than one value on a line, you can print2785a comma-separated sequence of values:27862787\begin{verbatim}2788print('+', '-')2789\end{verbatim}2790%2791By default, {\tt print} advances to the next line, but you2792can override that behavior and put a space at the end, like this:27932794\begin{verbatim}2795print('+', end=' ')2796print('-')2797\end{verbatim}2798%2799The output of these statements is \verb"'+ -'" on the same line.2800The output from the next print statement would begin on the next line.28012802\item Write a function that draws a similar grid2803with four rows and four columns.28042805\end{enumerate}28062807Solution: \url{http://thinkpython2.com/code/grid.py}.2808Credit: This exercise is based on an exercise in Oualline, {\em2809Practical C Programming, Third Edition}, O'Reilly Media, 1997.28102811\end{exercise}281228132814281528162817\chapter{Case study: interface design}2818\label{turtlechap}28192820This chapter presents a case study that demonstrates a process for2821designing functions that work together.28222823It introduces the {\tt turtle} module, which allows you to2824create images using turtle graphics. The {\tt turtle} module is2825included in most Python installations, but if you are running Python2826using PythonAnywhere, you won't be able to run the turtle examples (at2827least you couldn't when I wrote this).28282829If you have already installed Python on your computer, you should2830be able to run the examples. Otherwise, now is a good time2831to install. I have posted instructions at2832\url{http://tinyurl.com/thinkpython2e}.28332834Code examples from this chapter are available from2835\url{http://thinkpython2.com/code/polygon.py}.283628372838\section{The turtle module}2839\label{turtle}28402841To check whether you have the {\tt turtle} module, open the Python2842interpreter and type28432844\begin{verbatim}2845>>> import turtle2846>>> bob = turtle.Turtle()2847\end{verbatim}28482849When you run this code, it should create a new window2850with small arrow that represents the turtle. Close the window.28512852Create a file named {\tt mypolygon.py} and type in the following2853code:28542855\begin{verbatim}2856import turtle2857bob = turtle.Turtle()2858print(bob)2859turtle.mainloop()2860\end{verbatim}2861%2862The {\tt turtle} module (with a lowercase 't') provides a function2863called {\tt Turtle} (with an uppercase 'T') that creates a Turtle2864object, which we assign to a variable named {\tt bob}.2865Printing {\tt bob} displays something like:28662867\begin{verbatim}2868<turtle.Turtle object at 0xb7bfbf4c>2869\end{verbatim}2870%2871This means that {\tt bob} refers to an object with type2872{\tt Turtle}2873as defined in module {\tt turtle}.28742875\verb"mainloop" tells the window to wait for the user2876to do something, although in this case there's not much for2877the user to do except close the window.28782879Once you create a Turtle, you can call a {\bf method} to move it2880around the window. A method is similar to a function, but it2881uses slightly different syntax. For example, to move the turtle2882forward:28832884\begin{verbatim}2885bob.fd(100)2886\end{verbatim}2887%2888The method, {\tt fd}, is associated with the turtle2889object we're calling {\tt bob}.2890Calling a method is like making a request: you are asking {\tt bob}2891to move forward.28922893The argument of {\tt fd} is a distance in pixels, so the actual2894size depends on your display.28952896Other methods you can call on a Turtle are {\tt bk} to move2897backward, {\tt lt} for left turn, and {\tt rt} right turn. The2898argument for {\tt lt} and {\tt rt} is an angle in degrees.28992900Also, each Turtle is holding a pen, which is2901either down or up; if the pen is down, the Turtle leaves2902a trail when it moves. The methods {\tt pu} and {\tt pd}2903stand for ``pen up'' and ``pen down''.29042905To draw a right angle, add these lines to the program2906(after creating {\tt bob} and before calling \verb"mainloop"):29072908\begin{verbatim}2909bob.fd(100)2910bob.lt(90)2911bob.fd(100)2912\end{verbatim}2913%2914When you run this program, you should see {\tt bob} move east and then2915north, leaving two line segments behind.29162917Now modify the program to draw a square. Don't go on until2918you've got it working!29192920%\newpage29212922\section{Simple repetition}2923\label{repetition}2924\index{repetition}29252926Chances are you wrote something like this:29272928\begin{verbatim}2929bob.fd(100)2930bob.lt(90)29312932bob.fd(100)2933bob.lt(90)29342935bob.fd(100)2936bob.lt(90)29372938bob.fd(100)2939\end{verbatim}2940%2941We can do the same thing more concisely with a {\tt for} statement.2942Add this example to {\tt mypolygon.py} and run it again:2943\index{for loop}2944\index{loop!for}2945\index{statement!for}29462947\begin{verbatim}2948for i in range(4):2949print('Hello!')2950\end{verbatim}2951%2952You should see something like this:29532954\begin{verbatim}2955Hello!2956Hello!2957Hello!2958Hello!2959\end{verbatim}2960%2961This is the simplest use of the {\tt for} statement; we will see2962more later. But that should be enough to let you rewrite your2963square-drawing program. Don't go on until you do.29642965Here is a {\tt for} statement that draws a square:29662967\begin{verbatim}2968for i in range(4):2969bob.fd(100)2970bob.lt(90)2971\end{verbatim}2972%2973The syntax of a {\tt for} statement is similar to a function2974definition. It has a header that ends with a colon and an indented2975body. The body can contain any number of statements.29762977A {\tt for} statement is also called a {\bf loop} because2978the flow of execution runs through the body and then loops back2979to the top. In this case, it runs the body four times.2980\index{loop}29812982This version is actually a little different from the previous2983square-drawing code because it makes another turn after2984drawing the last side of the square. The extra turn takes2985more time, but it simplifies the code if we do the same thing2986every time through the loop. This version also has the effect2987of leaving the turtle back in the starting position, facing in2988the starting direction.29892990\section{Exercises}29912992The following is a series of exercises using TurtleWorld. They2993are meant to be fun, but they have a point, too. While you are2994working on them, think about what the point is.29952996The following sections have solutions to the exercises, so2997don't look until you have finished (or at least tried).29982999\begin{enumerate}30003001\item Write a function called {\tt square} that takes a parameter3002named {\tt t}, which is a turtle. It should use the turtle to draw3003a square.30043005Write a function call that passes {\tt bob} as an argument to3006{\tt square}, and then run the program again.30073008\item Add another parameter, named {\tt length}, to {\tt square}.3009Modify the body so length of the sides is {\tt length}, and then3010modify the function call to provide a second argument. Run the3011program again. Test your program with a range of values for {\tt3012length}.30133014\item Make a copy of {\tt square} and change the name to {\tt3015polygon}. Add another parameter named {\tt n} and modify the body3016so it draws an n-sided regular polygon. Hint: The exterior angles3017of an n-sided regular polygon are $360/n$ degrees. \index{polygon3018function} \index{function!polygon}30193020\item Write a function called {\tt circle} that takes a turtle,3021{\tt t}, and radius, {\tt r}, as parameters and that draws an3022approximate circle by calling {\tt polygon} with an appropriate3023length and number of sides. Test your function with a range of values3024of {\tt r}. \index{circle function} \index{function!circle}30253026Hint: figure out the circumference of the circle and make sure that3027{\tt length * n = circumference}.30283029\item Make a more general version of {\tt circle} called {\tt arc}3030that takes an additional parameter {\tt angle}, which determines3031what fraction of a circle to draw. {\tt angle} is in units of3032degrees, so when {\tt angle=360}, {\tt arc} should draw a complete3033circle.3034\index{arc function}3035\index{function!arc}30363037\end{enumerate}303830393040\section{Encapsulation}30413042The first exercise asks you to put your square-drawing code3043into a function definition and then call the function, passing3044the turtle as a parameter. Here is a solution:30453046\begin{verbatim}3047def square(t):3048for i in range(4):3049t.fd(100)3050t.lt(90)30513052square(bob)3053\end{verbatim}3054%3055The innermost statements, {\tt fd} and {\tt lt} are indented twice to3056show that they are inside the {\tt for} loop, which is inside the3057function definition. The next line, {\tt square(bob)}, is flush with3058the left margin, which indicates the end of both the {\tt for} loop3059and the function definition.30603061Inside the function, {\tt t} refers to the same turtle {\tt bob}, so3062{\tt t.lt(90)} has the same effect as {\tt bob.lt(90)}. In that3063case, why not3064call the parameter {\tt bob}? The idea is that {\tt t} can be any3065turtle, not just {\tt bob}, so you could create a second turtle and3066pass it as an argument to {\tt square}:30673068\begin{verbatim}3069alice = turtle.Turtle()3070square(alice)3071\end{verbatim}3072%3073Wrapping a piece of code up in a function is called {\bf3074encapsulation}. One of the benefits of encapsulation is that it3075attaches a name to the code, which serves as a kind of documentation.3076Another advantage is that if you re-use the code, it is more concise3077to call a function twice than to copy and paste the body!3078\index{encapsulation}307930803081\section{Generalization}30823083The next step is to add a {\tt length} parameter to {\tt square}.3084Here is a solution:30853086\begin{verbatim}3087def square(t, length):3088for i in range(4):3089t.fd(length)3090t.lt(90)30913092square(bob, 100)3093\end{verbatim}3094%3095Adding a parameter to a function is called {\bf generalization}3096because it makes the function more general: in the previous3097version, the square is always the same size; in this version3098it can be any size.3099\index{generalization}31003101The next step is also a generalization. Instead of drawing3102squares, {\tt polygon} draws regular polygons with any number of3103sides. Here is a solution:31043105\begin{verbatim}3106def polygon(t, n, length):3107angle = 360 / n3108for i in range(n):3109t.fd(length)3110t.lt(angle)31113112polygon(bob, 7, 70)3113\end{verbatim}3114%3115This example draws a 7-sided polygon with side length 70.31163117If you are using Python 2, the value of {\tt angle} might be off3118because of integer division. A simple solution is to compute3119{\tt angle = 360.0 / n}. Because the numerator is a floating-point3120number, the result is floating point.3121\index{Python 2}31223123When a function has more than a few numeric arguments, it is easy to3124forget what they are, or what order they should be in. In that case3125it is often a good idea to include the names of the parameters in the3126argument list:31273128\begin{verbatim}3129polygon(bob, n=7, length=70)3130\end{verbatim}3131%3132These are called {\bf keyword arguments} because they include3133the parameter names as ``keywords'' (not to be confused with3134Python keywords like {\tt while} and {\tt def}).3135\index{keyword argument}3136\index{argument!keyword}31373138This syntax makes the program more readable. It is also a reminder3139about how arguments and parameters work: when you call a function, the3140arguments are assigned to the parameters.314131423143\section{Interface design}31443145The next step is to write {\tt circle}, which takes a radius,3146{\tt r}, as a parameter. Here is a simple solution that uses3147{\tt polygon} to draw a 50-sided polygon:31483149\begin{verbatim}3150import math31513152def circle(t, r):3153circumference = 2 * math.pi * r3154n = 503155length = circumference / n3156polygon(t, n, length)3157\end{verbatim}3158%3159The first line computes the circumference of a circle with radius3160{\tt r} using the formula $2 \pi r$. Since we use {\tt math.pi}, we3161have to import {\tt math}. By convention, {\tt import} statements3162are usually at the beginning of the script.31633164{\tt n} is the number of line segments in our approximation of a circle,3165so {\tt length} is the length of each segment. Thus, {\tt polygon}3166draws a 50-sided polygon that approximates a circle with radius {\tt r}.31673168One limitation of this solution is that {\tt n} is a constant, which3169means that for very big circles, the line segments are too long, and3170for small circles, we waste time drawing very small segments. One3171solution would be to generalize the function by taking {\tt n} as3172a parameter. This would give the user (whoever calls {\tt circle})3173more control, but the interface would be less clean.3174\index{interface}31753176The {\bf interface} of a function is a summary of how it is used: what3177are the parameters? What does the function do? And what is the return3178value? An interface is ``clean'' if it allows the caller to do3179what they want without dealing with unnecessary details.31803181In this example, {\tt r} belongs in the interface because it3182specifies the circle to be drawn. {\tt n} is less appropriate3183because it pertains to the details of {\em how} the circle should3184be rendered.31853186Rather than clutter up the interface, it is better3187to choose an appropriate value of {\tt n}3188depending on {\tt circumference}:31893190\begin{verbatim}3191def circle(t, r):3192circumference = 2 * math.pi * r3193n = int(circumference / 3) + 33194length = circumference / n3195polygon(t, n, length)3196\end{verbatim}3197%3198Now the number of segments is an integer near {\tt circumference/3},3199so the length of each segment is approximately 3, which is small3200enough that the circles look good, but big enough to be efficient,3201and acceptable for any size circle.32023203Adding 3 to {\tt n} guarantees that the polygon has at least 3 sides.320432053206\section{Refactoring}3207\label{refactoring}3208\index{refactoring}32093210When I wrote {\tt circle}, I was able to re-use {\tt polygon}3211because a many-sided polygon is a good approximation of a circle.3212But {\tt arc} is not as cooperative; we can't use {\tt polygon}3213or {\tt circle} to draw an arc.32143215One alternative is to start with a copy3216of {\tt polygon} and transform it into {\tt arc}. The result3217might look like this:32183219\begin{verbatim}3220def arc(t, r, angle):3221arc_length = 2 * math.pi * r * angle / 3603222n = int(arc_length / 3) + 13223step_length = arc_length / n3224step_angle = angle / n32253226for i in range(n):3227t.fd(step_length)3228t.lt(step_angle)3229\end{verbatim}3230%3231The second half of this function looks like {\tt polygon}, but we3232can't re-use {\tt polygon} without changing the interface. We could3233generalize {\tt polygon} to take an angle as a third argument,3234but then {\tt polygon} would no longer be an appropriate name!3235Instead, let's call the more general function {\tt polyline}:32363237\begin{verbatim}3238def polyline(t, n, length, angle):3239for i in range(n):3240t.fd(length)3241t.lt(angle)3242\end{verbatim}3243%3244Now we can rewrite {\tt polygon} and {\tt arc} to use {\tt polyline}:32453246\begin{verbatim}3247def polygon(t, n, length):3248angle = 360.0 / n3249polyline(t, n, length, angle)32503251def arc(t, r, angle):3252arc_length = 2 * math.pi * r * angle / 3603253n = int(arc_length / 3) + 13254step_length = arc_length / n3255step_angle = float(angle) / n3256polyline(t, n, step_length, step_angle)3257\end{verbatim}3258%3259Finally, we can rewrite {\tt circle} to use {\tt arc}:32603261\begin{verbatim}3262def circle(t, r):3263arc(t, r, 360)3264\end{verbatim}3265%3266This process---rearranging a program to improve3267interfaces and facilitate code re-use---is called {\bf refactoring}.3268In this case, we noticed that there was similar code in {\tt arc} and3269{\tt polygon}, so we ``factored it out'' into {\tt polyline}.3270\index{refactoring}32713272If we had planned ahead, we might have written {\tt polyline} first3273and avoided refactoring, but often you don't know enough at the3274beginning of a project to design all the interfaces. Once you start3275coding, you understand the problem better. Sometimes refactoring is a3276sign that you have learned something.327732783279\section{A development plan}3280\index{development plan!encapsulation and generalization}32813282A {\bf development plan} is a process for writing programs. The3283process we used in this case study is ``encapsulation and3284generalization''. The steps of this process are:32853286\begin{enumerate}32873288\item Start by writing a small program with no function definitions.32893290\item Once you get the program working, identify a coherent piece of3291it, encapsulate the piece in a function and give it a name.32923293\item Generalize the function by adding appropriate parameters.32943295\item Repeat steps 1--3 until you have a set of working functions.3296Copy and paste working code to avoid retyping (and re-debugging).32973298\item Look for opportunities to improve the program by refactoring.3299For example, if you have similar code in several places, consider3300factoring it into an appropriately general function.33013302\end{enumerate}33033304This process has some drawbacks---we will see alternatives later---but3305it can be useful if you don't know ahead of time how to divide the3306program into functions. This approach lets you design as you go3307along.330833093310\section{docstring}3311\label{docstring}3312\index{docstring}33133314A {\bf docstring} is a string at the beginning of a function that3315explains the interface (``doc'' is short for ``documentation''). Here3316is an example:33173318\begin{verbatim}3319def polyline(t, n, length, angle):3320"""Draws n line segments with the given length and3321angle (in degrees) between them. t is a turtle.3322"""3323for i in range(n):3324t.fd(length)3325t.lt(angle)3326\end{verbatim}3327%3328By convention, all docstrings are triple-quoted strings, also known3329as multiline strings because the triple quotes allow the string3330to span more than one line.3331\index{quotation mark}3332\index{triple-quoted string}3333\index{string!triple-quoted}3334\index{multiline string}3335\index{string!multiline}33363337It is terse, but it contains the essential information3338someone would need to use this function. It explains concisely what3339the function does (without getting into the details of how it does3340it). It explains what effect each parameter has on the behavior of3341the function and what type each parameter should be (if it is not3342obvious).33433344Writing this kind of documentation is an important part of interface3345design. A well-designed interface should be simple to explain;3346if you have a hard time explaining one of your functions,3347maybe the interface could be improved.334833493350\section{Debugging}3351\index{debugging}3352\index{interface}33533354An interface is like a contract between a function and a caller.3355The caller agrees to provide certain parameters and the function3356agrees to do certain work.33573358For example, {\tt polyline} requires four arguments: {\tt t} has to be3359a Turtle; {\tt n} has to be an3360integer; {\tt length} should be a positive number; and {\tt3361angle} has to be a number, which is understood to be in degrees.33623363These requirements are called {\bf preconditions} because they3364are supposed to be true before the function starts executing.3365Conversely, conditions at the end of the function are3366{\bf postconditions}. Postconditions include the intended3367effect of the function (like drawing line segments) and any3368side effects (like moving the Turtle or making other changes).3369\index{precondition}3370\index{postcondition}33713372Preconditions are the responsibility of the caller. If the caller3373violates a (properly documented!) precondition and the function3374doesn't work correctly, the bug is in the caller, not the function.33753376If the preconditions are satisfied and the postconditions are3377not, the bug is in the function. If your pre- and postconditions3378are clear, they can help with debugging.337933803381\section{Glossary}33823383\begin{description}33843385\item[method:] A function that is associated with an object and called3386using dot notation.3387\index{method}33883389\item[loop:] A part of a program that can run repeatedly.3390\index{loop}33913392\item[encapsulation:] The process of transforming a sequence of3393statements into a function definition.3394\index{encapsulation}33953396\item[generalization:] The process of replacing something3397unnecessarily specific (like a number) with something appropriately3398general (like a variable or parameter).3399\index{generalization}34003401\item[keyword argument:] An argument that includes the name of3402the parameter as a ``keyword''.3403\index{keyword argument}3404\index{argument!keyword}34053406\item[interface:] A description of how to use a function, including3407the name and descriptions of the arguments and return value.3408\index{interface}34093410\item[refactoring:] The process of modifying a working program to3411improve function interfaces and other qualities of the code.3412\index{refactoring}34133414\item[development plan:] A process for writing programs.3415\index{development plan}34163417\item[docstring:] A string that appears at the top of a function3418definition to document the function's interface.3419\index{docstring}34203421\item[precondition:] A requirement that should be satisfied by3422the caller before a function starts.3423\index{precondition}34243425\item[postcondition:] A requirement that should be satisfied by3426the function before it ends.3427\index{precondition}34283429\end{description}343034313432\section{Exercises}34333434\begin{exercise}34353436Download the code in this chapter from3437\url{http://thinkpython2.com/code/polygon.py}.34383439\begin{enumerate}34403441\item Draw a stack diagram that shows the state of the program3442while executing {\tt circle(bob, radius)}. You can do the3443arithmetic by hand or add {\tt print} statements to the code.3444\index{stack diagram}34453446\item The version of {\tt arc} in Section~\ref{refactoring} is not3447very accurate because the linear approximation of the3448circle is always outside the true circle. As a result,3449the Turtle ends up a few pixels away from the correct3450destination. My solution shows a way to reduce3451the effect of this error. Read the code and see if it makes3452sense to you. If you draw a diagram, you might see how it works.34533454\end{enumerate}34553456\end{exercise}34573458\begin{figure}3459\centerline3460{\includegraphics[scale=0.8]{figs/flowers.pdf}}3461\caption{Turtle flowers.}3462\label{fig.flowers}3463\end{figure}34643465\begin{exercise}3466\index{flower}34673468Write an appropriately general set of functions that3469can draw flowers as in Figure~\ref{fig.flowers}.34703471Solution: \url{http://thinkpython2.com/code/flower.py},3472also requires \url{http://thinkpython2.com/code/polygon.py}.34733474\end{exercise}34753476\begin{figure}3477\centerline3478{\includegraphics[scale=0.8]{figs/pies.pdf}}3479\caption{Turtle pies.}3480\label{fig.pies}3481\end{figure}348234833484\begin{exercise}3485\index{pie}34863487Write an appropriately general set of functions that3488can draw shapes as in Figure~\ref{fig.pies}.34893490Solution: \url{http://thinkpython2.com/code/pie.py}.34913492\end{exercise}34933494\begin{exercise}3495\index{alphabet}3496\index{turtle typewriter}3497\index{typewriter, turtle}34983499The letters of the alphabet can be constructed from a moderate number3500of basic elements, like vertical and horizontal lines and a few3501curves. Design an alphabet that can be drawn with a minimal3502number of basic elements and then write functions that draw the letters.35033504You should write one function for each letter, with names3505\verb"draw_a", \verb"draw_b", etc., and put your functions3506in a file named {\tt letters.py}. You can download a3507``turtle typewriter'' from \url{http://thinkpython2.com/code/typewriter.py}3508to help you test your code.35093510You can get a solution from \url{http://thinkpython2.com/code/letters.py};3511it also requires3512\url{http://thinkpython2.com/code/polygon.py}.35133514\end{exercise}35153516\begin{exercise}35173518Read about spirals at \url{http://en.wikipedia.org/wiki/Spiral}; then3519write a program that draws an Archimedian spiral (or one of the other3520kinds). Solution: \url{http://thinkpython2.com/code/spiral.py}.3521\index{spiral}3522\index{Archimedian spiral}35233524\end{exercise}352535263527\chapter{Conditionals and recursion}35283529The main topic of this chapter is the {\tt if} statement, which3530executes different code depending on the state of the program.3531But first I want to introduce two new operators: floor division3532and modulus.353335343535\section{Floor division and modulus}35363537The {\bf floor division} operator, \verb"//", divides3538two numbers and rounds down to an integer. For example, suppose the3539run time of a movie is 105 minutes. You might want to know how3540long that is in hours. Conventional division3541returns a floating-point number:35423543\begin{verbatim}3544>>> minutes = 1053545>>> minutes / 6035461.753547\end{verbatim}35483549But we don't normally write hours with decimal points. Floor3550division returns the integer number of hours, rounding down:35513552\begin{verbatim}3553>>> minutes = 1053554>>> hours = minutes // 603555>>> hours355613557\end{verbatim}35583559To get the remainder, you could subtract off one hour in minutes:35603561\begin{verbatim}3562>>> remainder = minutes - hours * 603563>>> remainder3564453565\end{verbatim}35663567\index{floor division}3568\index{floating-point division}3569\index{division!floor}3570\index{division!floating-point}3571\index{modulus operator}3572\index{operator!modulus}35733574An alternative is to use the {\bf modulus operator}, \verb"%", which3575divides two numbers and returns the remainder.35763577\begin{verbatim}3578>>> remainder = minutes % 603579>>> remainder3580453581\end{verbatim}3582%3583The modulus operator is more useful than it seems. For3584example, you can check whether one number is divisible by another---if3585{\tt x \% y} is zero, then {\tt x} is divisible by {\tt y}.3586\index{divisibility}35873588Also, you can extract the right-most digit3589or digits from a number. For example, {\tt x \% 10} yields the3590right-most digit of {\tt x} (in base 10). Similarly {\tt x \% 100}3591yields the last two digits.35923593If you are using Python 2, division works differently. The3594division operator, \verb"/", performs floor division if both3595operands are integers, and floating-point division if either3596operand is a {\tt float}.3597\index{Python 2}359835993600\section{Boolean expressions}3601\index{boolean expression}3602\index{expression!boolean}3603\index{logical operator}3604\index{operator!logical}36053606A {\bf boolean expression} is an expression that is either true3607or false. The following examples use the3608operator {\tt ==}, which compares two operands and produces3609{\tt True} if they are equal and {\tt False} otherwise:36103611\begin{verbatim}3612>>> 5 == 53613True3614>>> 5 == 63615False3616\end{verbatim}3617%3618{\tt True} and {\tt False} are special3619values that belong to the type {\tt bool}; they are not strings:3620\index{True special value}3621\index{False special value}3622\index{special value!True}3623\index{special value!False}3624\index{bool type}3625\index{type!bool}36263627\begin{verbatim}3628>>> type(True)3629<class 'bool'>3630>>> type(False)3631<class 'bool'>3632\end{verbatim}3633%3634The {\tt ==} operator is one of the {\bf relational operators}; the3635others are:36363637\begin{verbatim}3638x != y # x is not equal to y3639x > y # x is greater than y3640x < y # x is less than y3641x >= y # x is greater than or equal to y3642x <= y # x is less than or equal to y3643\end{verbatim}3644%3645Although these operations are probably familiar to you, the Python3646symbols are different from the mathematical symbols. A common error3647is to use a single equal sign ({\tt =}) instead of a double equal sign3648({\tt ==}). Remember that {\tt =} is an assignment operator and3649{\tt ==} is a relational operator. There is no such thing as3650{\tt =<} or {\tt =>}.3651\index{relational operator}3652\index{operator!relational}365336543655\section {Logical operators}3656\index{logical operator}3657\index{operator!logical}36583659There are three {\bf logical operators}: {\tt and}, {\tt3660or}, and {\tt not}. The semantics (meaning) of these operators is3661similar to their meaning in English. For example,3662{\tt x > 0 and x < 10} is true only if {\tt x} is greater than 03663{\em and} less than 10.3664\index{and operator}3665\index{or operator}3666\index{not operator}3667\index{operator!and}3668\index{operator!or}3669\index{operator!not}36703671{\tt n\%2 == 0 or n\%3 == 0} is true if {\em either or both} of the3672conditions is true, that is, if the number is divisible by 2 {\em or}36733.36743675Finally, the {\tt not} operator negates a boolean3676expression, so {\tt not (x > y)} is true if {\tt x > y} is false,3677that is, if {\tt x} is less than or equal to {\tt y}.36783679Strictly speaking, the operands of the logical operators should be3680boolean expressions, but Python is not very strict.3681Any nonzero number is interpreted as {\tt True}:36823683\begin{verbatim}3684>>> 42 and True3685True3686\end{verbatim}3687%3688This flexibility can be useful, but there are some subtleties to3689it that might be confusing. You might want to avoid it (unless3690you know what you are doing).369136923693\section{Conditional execution}3694\label{conditional.execution}36953696\index{conditional statement}3697\index{statement!conditional}3698\index{if statement}3699\index{statement!if}3700\index{conditional execution}3701In order to write useful programs, we almost always need the ability3702to check conditions and change the behavior of the program3703accordingly. {\bf Conditional statements} give us this ability. The3704simplest form is the {\tt if} statement:37053706\begin{verbatim}3707if x > 0:3708print('x is positive')3709\end{verbatim}3710%3711The boolean expression after {\tt if} is3712called the {\bf condition}. If it is true, the indented3713statement runs. If not, nothing happens.3714\index{condition}3715\index{compound statement}3716\index{statement!compound}37173718{\tt if} statements have the same structure as function definitions:3719a header followed by an indented body. Statements like this are3720called {\bf compound statements}.37213722There is no limit on the number of statements that can appear in3723the body, but there has to be at least one.3724Occasionally, it is useful to have a body with no statements (usually3725as a place keeper for code you haven't written yet). In that3726case, you can use the {\tt pass} statement, which does nothing.3727\index{pass statement}3728\index{statement!pass}37293730\begin{verbatim}3731if x < 0:3732pass # TODO: need to handle negative values!3733\end{verbatim}3734%37353736\section{Alternative execution}3737\label{alternative.execution}3738\index{alternative execution}3739\index{else keyword}3740\index{keyword!else}37413742A second form of the {\tt if} statement is ``alternative execution'',3743in which there are two possibilities and the condition determines3744which one runs. The syntax looks like this:37453746\begin{verbatim}3747if x % 2 == 0:3748print('x is even')3749else:3750print('x is odd')3751\end{verbatim}3752%3753If the remainder when {\tt x} is divided by 2 is 0, then we know that3754{\tt x} is even, and the program displays an appropriate message. If3755the condition is false, the second set of statements runs.3756Since the condition must be true or false, exactly one of the3757alternatives will run. The alternatives are called {\bf3758branches}, because they are branches in the flow of execution.3759\index{branch}3760376137623763\section{Chained conditionals}3764\index{chained conditional}3765\index{conditional!chained}37663767Sometimes there are more than two possibilities and we need more than3768two branches. One way to express a computation like that is a {\bf3769chained conditional}:37703771\begin{verbatim}3772if x < y:3773print('x is less than y')3774elif x > y:3775print('x is greater than y')3776else:3777print('x and y are equal')3778\end{verbatim}3779%3780{\tt elif} is an abbreviation of ``else if''. Again, exactly one3781branch will run. There is no limit on the number of {\tt3782elif} statements. If there is an {\tt else} clause, it has to be3783at the end, but there doesn't have to be one.3784\index{elif keyword}3785\index{keyword!elif}37863787\begin{verbatim}3788if choice == 'a':3789draw_a()3790elif choice == 'b':3791draw_b()3792elif choice == 'c':3793draw_c()3794\end{verbatim}3795%3796Each condition is checked in order. If the first is false,3797the next is checked, and so on. If one of them is3798true, the corresponding branch runs and the statement3799ends. Even if more than one condition is true, only the3800first true branch runs.380138023803\section{Nested conditionals}3804\index{nested conditional}3805\index{conditional!nested}38063807One conditional can also be nested within another. We could have3808written the example in the previous section like this:38093810\begin{verbatim}3811if x == y:3812print('x and y are equal')3813else:3814if x < y:3815print('x is less than y')3816else:3817print('x is greater than y')3818\end{verbatim}3819%3820The outer conditional contains two branches. The3821first branch contains a simple statement. The second branch3822contains another {\tt if} statement, which has two branches of its3823own. Those two branches are both simple statements,3824although they could have been conditional statements as well.38253826Although the indentation of the statements makes the structure3827apparent, {\bf nested conditionals} become difficult to read very3828quickly. It is a good idea to avoid them when you can.38293830Logical operators often provide a way to simplify nested conditional3831statements. For example, we can rewrite the following code using a3832single conditional:38333834\begin{verbatim}3835if 0 < x:3836if x < 10:3837print('x is a positive single-digit number.')3838\end{verbatim}3839%3840The {\tt print} statement runs only if we make it past both3841conditionals, so we can get the same effect with the {\tt and} operator:38423843\begin{verbatim}3844if 0 < x and x < 10:3845print('x is a positive single-digit number.')3846\end{verbatim}38473848For this kind of condition, Python provides a more concise option:38493850\begin{verbatim}3851if 0 < x < 10:3852print('x is a positive single-digit number.')3853\end{verbatim}385438553856\section{Recursion}3857\label{recursion}3858\index{recursion}38593860It is legal for one function to call another;3861it is also legal for a function to call itself. It may not be obvious3862why that is a good thing, but it turns out to be one of the most3863magical things a program can do.3864For example, look at the following function:38653866\begin{verbatim}3867def countdown(n):3868if n <= 0:3869print('Blastoff!')3870else:3871print(n)3872countdown(n-1)3873\end{verbatim}3874%3875If {\tt n} is 0 or negative, it outputs the word, ``Blastoff!''3876Otherwise, it outputs {\tt n} and then calls a function named {\tt3877countdown}---itself---passing {\tt n-1} as an argument.38783879What happens if we call this function like this?38803881\begin{verbatim}3882>>> countdown(3)3883\end{verbatim}3884%3885The execution of {\tt countdown} begins with {\tt n=3}, and since3886{\tt n} is greater than 0, it outputs the value 3, and then calls itself...38873888\begin{quote}3889The execution of {\tt countdown} begins with {\tt n=2}, and since3890{\tt n} is greater than 0, it outputs the value 2, and then calls itself...38913892\begin{quote}3893The execution of {\tt countdown} begins with {\tt n=1}, and since3894{\tt n} is greater than 0, it outputs the value 1, and then calls itself...38953896\begin{quote}3897The execution of {\tt countdown} begins with {\tt n=0}, and since {\tt3898n} is not greater than 0, it outputs the word, ``Blastoff!'' and then3899returns.3900\end{quote}39013902The {\tt countdown} that got {\tt n=1} returns.3903\end{quote}39043905The {\tt countdown} that got {\tt n=2} returns.3906\end{quote}39073908The {\tt countdown} that got {\tt n=3} returns.39093910And then you're back in \verb"__main__". So, the3911total output looks like this:3912\index{main}39133914\begin{verbatim}3915339162391713918Blastoff!3919\end{verbatim}3920%3921A function that calls itself is {\bf recursive}; the process of3922executing it is called {\bf recursion}.3923\index{recursion}3924\index{function!recursive}39253926As another example, we can write a function that prints a3927string {\tt n} times.39283929\begin{verbatim}3930def print_n(s, n):3931if n <= 0:3932return3933print(s)3934print_n(s, n-1)3935\end{verbatim}3936%3937If {\tt n <= 0} the {\bf return statement} exits the function. The3938flow of execution immediately returns to the caller, and the remaining3939lines of the function don't run.3940\index{return statement}3941\index{statement!return}39423943The rest of the function is similar to {\tt countdown}: it displays3944{\tt s} and then calls itself to display {\tt s} $n-1$ additional3945times. So the number of lines of output is {\tt 1 + (n - 1)}, which3946adds up to {\tt n}.39473948For simple examples like this, it is probably easier to use a {\tt3949for} loop. But we will see examples later that are hard to write3950with a {\tt for} loop and easy to write with recursion, so it is3951good to start early.3952\index{for loop}3953\index{loop!for}395439553956\section{Stack diagrams for recursive functions}3957\label{recursive.stack}3958\index{stack diagram}3959\index{function frame}3960\index{frame}39613962In Section~\ref{stackdiagram}, we used a stack diagram to represent3963the state of a program during a function call. The same kind of3964diagram can help interpret a recursive function.39653966Every time a function gets called, Python creates a3967frame to contain the function's local variables and parameters.3968For a recursive function, there might be more than one frame on the3969stack at the same time.39703971Figure~\ref{fig.stack2} shows a stack diagram for {\tt countdown} called with3972{\tt n = 3}.39733974\begin{figure}3975\centerline3976{\includegraphics[scale=0.8]{figs/stack2.pdf}}3977\caption{Stack diagram.}3978\label{fig.stack2}3979\end{figure}398039813982As usual, the top of the stack is the frame for \verb"__main__".3983It is empty because we did not create any variables in3984\verb"__main__" or pass any arguments to it.3985\index{base case}3986\index{recursion!base case}39873988The four {\tt countdown} frames have different values for the3989parameter {\tt n}. The bottom of the stack, where {\tt n=0}, is3990called the {\bf base case}. It does not make a recursive call, so3991there are no more frames.39923993As an exercise, draw a stack diagram for \verb"print_n" called with3994\verb"s = 'Hello'" and {\tt n=2}.3995Then write a function called \verb"do_n" that takes a function3996object and a number, {\tt n}, as arguments, and that calls3997the given function {\tt n} times.399839994000\section{Infinite recursion}4001\index{infinite recursion}4002\index{recursion!infinite}4003\index{runtime error}4004\index{error!runtime}4005\index{traceback}40064007If a recursion never reaches a base case, it goes on making4008recursive calls forever, and the program never terminates. This is4009known as {\bf infinite recursion}, and it is generally not4010a good idea. Here is a minimal program with an infinite recursion:40114012\begin{verbatim}4013def recurse():4014recurse()4015\end{verbatim}4016%4017In most programming environments, a program with infinite recursion4018does not really run forever. Python reports an error4019message when the maximum recursion depth is reached:4020\index{exception!RuntimeError}4021\index{RuntimeError}40224023\begin{verbatim}4024File "<stdin>", line 2, in recurse4025File "<stdin>", line 2, in recurse4026File "<stdin>", line 2, in recurse4027.4028.4029.4030File "<stdin>", line 2, in recurse4031RuntimeError: Maximum recursion depth exceeded4032\end{verbatim}4033%4034This traceback is a little bigger than the one we saw in the4035previous chapter. When the error occurs, there are 10004036{\tt recurse} frames on the stack!40374038If you encounter an infinite recursion by accident, review4039your function to confirm that there is a base case that does not4040make a recursive call. And if there is a base case, check whether4041you are guaranteed to reach it.404240434044\section{Keyboard input}4045\index{keyboard input}40464047The programs we have written so far accept no input from the user.4048They just do the same thing every time.40494050Python provides a built-in function called {\tt input} that4051stops the program and4052waits for the user to type something. When the user presses {\sf4053Return} or {\sf Enter}, the program resumes and \verb"input"4054returns what the user typed as a string. In Python 2, the same4055function is called \verb"raw_input".4056\index{Python 2}4057\index{input function}4058\index{function!input}40594060\begin{verbatim}4061>>> text = input()4062What are you waiting for?4063>>> text4064'What are you waiting for?'4065\end{verbatim}4066%4067Before getting input from the user, it is a good idea to print a4068prompt telling the user what to type. \verb"input" can take a4069prompt as an argument:4070\index{prompt}40714072\begin{verbatim}4073>>> name = input('What...is your name?\n')4074What...is your name?4075Arthur, King of the Britons!4076>>> name4077'Arthur, King of the Britons!'4078\end{verbatim}4079%4080The sequence \verb"\n" at the end of the prompt represents a {\bf4081newline}, which is a special character that causes a line break.4082That's why the user's input appears below the prompt. \index{newline}40834084If you expect the user to type an integer, you can try to convert4085the return value to {\tt int}:40864087\begin{verbatim}4088>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'4089>>> speed = input(prompt)4090What...is the airspeed velocity of an unladen swallow?4091424092>>> int(speed)4093424094\end{verbatim}4095%4096But if the user types something other than a string of digits,4097you get an error:40984099\begin{verbatim}4100>>> speed = input(prompt)4101What...is the airspeed velocity of an unladen swallow?4102What do you mean, an African or a European swallow?4103>>> int(speed)4104ValueError: invalid literal for int() with base 104105\end{verbatim}4106%4107We will see how to handle this kind of error later.4108\index{ValueError}4109\index{exception!ValueError}411041114112\section{Debugging}4113\label{whitespace}4114\index{debugging}4115\index{traceback}41164117When a syntax or runtime error occurs, the error message contains4118a lot of information, but it can be overwhelming. The most4119useful parts are usually:41204121\begin{itemize}41224123\item What kind of error it was, and41244125\item Where it occurred.41264127\end{itemize}41284129Syntax errors are usually easy to find, but there are a few4130gotchas. Whitespace errors can be tricky because spaces and4131tabs are invisible and we are used to ignoring them.4132\index{whitespace}41334134\begin{verbatim}4135>>> x = 54136>>> y = 64137File "<stdin>", line 14138y = 64139^4140IndentationError: unexpected indent4141\end{verbatim}4142%4143In this example, the problem is that the second line is indented by4144one space. But the error message points to {\tt y}, which is4145misleading. In general, error messages indicate where the problem was4146discovered, but the actual error might be earlier in the code,4147sometimes on a previous line.4148\index{error!runtime}4149\index{runtime error}41504151The same is true of runtime errors. Suppose you are trying4152to compute a signal-to-noise ratio in decibels. The formula4153is $SNR_{db} = 10 \log_{10} (P_{signal} / P_{noise})$. In Python,4154you might write something like this:41554156\begin{verbatim}4157import math4158signal_power = 94159noise_power = 104160ratio = signal_power // noise_power4161decibels = 10 * math.log10(ratio)4162print(decibels)4163\end{verbatim}4164%4165When you run this program, you get an exception:4166%4167\index{exception!OverflowError}4168\index{OverflowError}41694170\begin{verbatim}4171Traceback (most recent call last):4172File "snr.py", line 5, in ?4173decibels = 10 * math.log10(ratio)4174ValueError: math domain error4175\end{verbatim}4176%4177The error message indicates line 5, but there is nothing4178wrong with that line. To find the real error, it might be4179useful to print the value of {\tt ratio}, which turns out to4180be 0. The problem is in line 4, which uses floor division4181instead of floating-point division.4182\index{floor division}4183\index{division!floor}41844185You should take the time to read error messages carefully, but don't4186assume that everything they say is correct.418741884189\section{Glossary}41904191\begin{description}41924193\item[floor division:] An operator, denoted {\tt //}, that divides two4194numbers and rounds down (toward negative infinity) to an integer.4195\index{floor division}4196\index{division!floor}41974198\item[modulus operator:] An operator, denoted with a percent sign4199({\tt \%}), that works on integers and returns the remainder when one4200number is divided by another.4201\index{modulus operator}4202\index{operator!modulus}42034204\item[boolean expression:] An expression whose value is either4205{\tt True} or {\tt False}.4206\index{boolean expression}4207\index{expression!boolean}42084209\item[relational operator:] One of the operators that compares4210its operands: {\tt ==}, {\tt !=}, {\tt >}, {\tt <}, {\tt >=}, and {\tt <=}.42114212\item[logical operator:] One of the operators that combines boolean4213expressions: {\tt and}, {\tt or}, and {\tt not}.42144215\item[conditional statement:] A statement that controls the flow of4216execution depending on some condition.4217\index{conditional statement}4218\index{statement!conditional}42194220\item[condition:] The boolean expression in a conditional statement4221that determines which branch runs.4222\index{condition}42234224\item[compound statement:] A statement that consists of a header4225and a body. The header ends with a colon (:). The body is indented4226relative to the header.4227\index{compound statement}42284229\item[branch:] One of the alternative sequences of statements in4230a conditional statement.4231\index{branch}42324233\item[chained conditional:] A conditional statement with a series4234of alternative branches.4235\index{chained conditional}4236\index{conditional!chained}42374238\item[nested conditional:] A conditional statement that appears4239in one of the branches of another conditional statement.4240\index{nested conditional}4241\index{conditional!nested}42424243\item[return statement:] A statement that causes a function to4244end immediately and return to the caller.42454246\item[recursion:] The process of calling the function that is4247currently executing.4248\index{recursion}42494250\item[base case:] A conditional branch in a4251recursive function that does not make a recursive call.4252\index{base case}42534254\item[infinite recursion:] A recursion that doesn't have a4255base case, or never reaches it. Eventually, an infinite recursion4256causes a runtime error.4257\index{infinite recursion}42584259\end{description}42604261\section{Exercises}42624263\begin{exercise}42644265The {\tt time} module provides a function, also named {\tt time}, that4266returns the current Greenwich Mean Time in ``the epoch'', which is4267an arbitrary time used as a reference point. On UNIX systems, the4268epoch is 1 January 1970.42694270\begin{verbatim}4271>>> import time4272>>> time.time()42731437746094.57359584274\end{verbatim}42754276Write a script that reads the current time and converts it to4277a time of day in hours, minutes, and seconds, plus the number of4278days since the epoch.42794280\end{exercise}428142824283\begin{exercise}4284\index{Fermat's Last Theorem}42854286Fermat's Last Theorem says that there are no positive integers4287$a$, $b$, and $c$ such that42884289\[ a^n + b^n = c^n \]4290%4291for any values of $n$ greater than 2.42924293\begin{enumerate}42944295\item Write a function named \verb"check_fermat" that takes four4296parameters---{\tt a}, {\tt b}, {\tt c} and {\tt n}---and4297checks to see if Fermat's theorem holds. If4298$n$ is greater than 2 and42994300\[a^n + b^n = c^n \]4301%4302the program should print, ``Holy smokes, Fermat was wrong!''4303Otherwise the program should print, ``No, that doesn't work.''43044305\item Write a function that prompts the user to input values4306for {\tt a}, {\tt b}, {\tt c} and {\tt n}, converts them to4307integers, and uses \verb"check_fermat" to check whether they4308violate Fermat's theorem.43094310\end{enumerate}43114312\end{exercise}431343144315\begin{exercise}4316\index{triangle}43174318If you are given three sticks, you may or may not be able to arrange4319them in a triangle. For example, if one of the sticks is 12 inches4320long and the other two are one inch long, you will4321not be able to get the short sticks to meet in the middle. For any4322three lengths, there is a simple test to see if it is possible to form4323a triangle:43244325\begin{quotation}4326If any of the three lengths is greater than the sum of the other4327two, then you cannot form a triangle. Otherwise, you4328can. (If the sum of two lengths equals the third, they form4329what is called a ``degenerate'' triangle.)4330\end{quotation}43314332\begin{enumerate}43334334\item Write a function named \verb"is_triangle" that takes three4335integers as arguments, and that prints either ``Yes'' or ``No'', depending4336on whether you can or cannot form a triangle from sticks with the4337given lengths.43384339\item Write a function that prompts the user to input three stick4340lengths, converts them to integers, and uses \verb"is_triangle" to4341check whether sticks with the given lengths can form a triangle.43424343\end{enumerate}43444345\end{exercise}43464347\begin{exercise}4348What is the output of the following program?4349Draw a stack diagram that shows the state of the program4350when it prints the result.43514352\begin{verbatim}4353def recurse(n, s):4354if n == 0:4355print(s)4356else:4357recurse(n-1, n+s)43584359recurse(3, 0)4360\end{verbatim}43614362\begin{enumerate}43634364\item What would happen if you called this function like this: {\tt4365recurse(-1, 0)}?43664367\item Write a docstring that explains everything someone would need to4368know in order to use this function (and nothing else).43694370\end{enumerate}43714372\end{exercise}437343744375The following exercises use the {\tt turtle} module, described in4376Chapter~\ref{turtlechap}:4377\index{TurtleWorld}43784379\begin{exercise}43804381Read the following function and see if you can figure out4382what it does (see the examples in Chapter~\ref{turtlechap}). Then run it4383and see if you got it right.43844385\begin{verbatim}4386def draw(t, length, n):4387if n == 0:4388return4389angle = 504390t.fd(length*n)4391t.lt(angle)4392draw(t, length, n-1)4393t.rt(2*angle)4394draw(t, length, n-1)4395t.lt(angle)4396t.bk(length*n)4397\end{verbatim}43984399\end{exercise}440044014402\begin{figure}4403\centerline4404{\includegraphics[scale=0.8]{figs/koch.pdf}}4405\caption{A Koch curve.}4406\label{fig.koch}4407\end{figure}44084409\begin{exercise}4410\index{Koch curve}44114412The Koch curve is a fractal that looks something like4413Figure~\ref{fig.koch}. To draw a Koch curve with length $x$, all you4414have to do is44154416\begin{enumerate}44174418\item Draw a Koch curve with length $x/3$.44194420\item Turn left 60 degrees.44214422\item Draw a Koch curve with length $x/3$.44234424\item Turn right 120 degrees.44254426\item Draw a Koch curve with length $x/3$.44274428\item Turn left 60 degrees.44294430\item Draw a Koch curve with length $x/3$.44314432\end{enumerate}44334434The exception is if $x$ is less than 3: in that case,4435you can just draw a straight line with length $x$.44364437\begin{enumerate}44384439\item Write a function called {\tt koch} that takes a turtle and4440a length as parameters, and that uses the turtle to draw a Koch4441curve with the given length.44424443\item Write a function called {\tt snowflake} that draws three4444Koch curves to make the outline of a snowflake.44454446Solution: \url{http://thinkpython2.com/code/koch.py}.44474448\item The Koch curve can be generalized in several ways. See4449\url{http://en.wikipedia.org/wiki/Koch_snowflake} for examples and4450implement your favorite.44514452\end{enumerate}4453\end{exercise}445444554456\chapter{Fruitful functions}4457\label{fruitchap}44584459Many of the Python functions we have used, such as the math4460functions, produce return values. But the functions we've written4461are all void: they have an effect, like printing a value4462or moving a turtle, but they don't have a return value. In4463this chapter you will learn to write fruitful functions.446444654466\section{Return values}4467\index{return value}44684469Calling the function generates a return4470value, which we usually assign to a variable or use as part of an4471expression.44724473\begin{verbatim}4474e = math.exp(1.0)4475height = radius * math.sin(radians)4476\end{verbatim}4477%4478The functions we have written so far are void. Speaking casually,4479they have no return value; more precisely,4480their return value is {\tt None}.44814482In this chapter, we are (finally) going to write fruitful functions.4483The first example is {\tt area}, which returns the area of a circle4484with the given radius:44854486\begin{verbatim}4487def area(radius):4488a = math.pi * radius**24489return a4490\end{verbatim}4491%4492We have seen the {\tt return} statement before, but in a fruitful4493function the {\tt return} statement includes4494an expression. This statement means: ``Return immediately from4495this function and use the following expression as a return value.''4496The expression can be arbitrarily complicated, so we could4497have written this function more concisely:4498\index{return statement}4499\index{statement!return}45004501\begin{verbatim}4502def area(radius):4503return math.pi * radius**24504\end{verbatim}4505%4506On the other hand, {\bf temporary variables} like {\tt a} can make4507debugging easier.4508\index{temporary variable}4509\index{variable!temporary}45104511Sometimes it is useful to have multiple return statements, one in each4512branch of a conditional:45134514\begin{verbatim}4515def absolute_value(x):4516if x < 0:4517return -x4518else:4519return x4520\end{verbatim}4521%4522Since these {\tt return} statements are in an alternative conditional,4523only one runs.45244525As soon as a return statement runs, the function4526terminates without executing any subsequent statements.4527Code that appears after a {\tt return} statement, or any other place4528the flow of execution can never reach, is called {\bf dead code}.4529\index{dead code}45304531In a fruitful function, it is a good idea to ensure4532that every possible path through the program hits a4533{\tt return} statement. For example:45344535\begin{verbatim}4536def absolute_value(x):4537if x < 0:4538return -x4539if x > 0:4540return x4541\end{verbatim}4542%4543This function is incorrect because if {\tt x} happens to be 0,4544neither condition is true, and the function ends without hitting a4545{\tt return} statement. If the flow of execution gets to the end4546of a function, the return value is {\tt None}, which is not4547the absolute value of 0.4548\index{None special value}4549\index{special value!None}45504551\begin{verbatim}4552>>> print(absolute_value(0))4553None4554\end{verbatim}4555%4556By the way, Python provides a built-in function called4557{\tt abs} that computes absolute values.4558\index{abs function}4559\index{function!abs}45604561As an exercise, write a {\tt compare} function that4562takes two values, {\tt x} and {\tt y}, and returns {\tt 1} if {\tt x > y},4563{\tt 0} if {\tt x == y}, and {\tt -1} if {\tt x < y}.4564\index{compare function}4565\index{function!compare}456645674568\section{Incremental development}4569\label{incremental.development}4570\index{development plan!incremental}45714572As you write larger functions, you might find yourself4573spending more time debugging.45744575To deal with increasingly complex programs,4576you might want to try a process called4577{\bf incremental development}. The goal of incremental development4578is to avoid long debugging sessions by adding and testing only4579a small amount of code at a time.4580\index{testing!incremental development}4581\index{Pythagorean theorem}45824583As an example, suppose you want to find the distance between two4584points, given by the coordinates $(x_1, y_1)$ and $(x_2, y_2)$.4585By the Pythagorean theorem, the distance is:45864587\begin{displaymath}4588\mathrm{distance} = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}4589\end{displaymath}4590%4591The first step is to consider what a {\tt distance} function should4592look like in Python. In other words, what are the inputs (parameters)4593and what is the output (return value)?45944595In this case, the inputs are two points, which you can represent4596using four numbers. The return value is the distance represented by4597a floating-point value.45984599Immediately you can write an outline of the function:46004601\begin{verbatim}4602def distance(x1, y1, x2, y2):4603return 0.04604\end{verbatim}4605%4606Obviously, this version doesn't compute distances; it always returns4607zero. But it is syntactically correct, and it runs, which means that4608you can test it before you make it more complicated.46094610To test the new function, call it with sample arguments:46114612\begin{verbatim}4613>>> distance(1, 2, 4, 6)46140.04615\end{verbatim}4616%4617I chose these values so that the horizontal distance is 3 and the4618vertical distance is 4; that way, the result is 5, the hypotenuse4619of a 3-4-5 triangle. When testing a function, it is4620useful to know the right answer.4621\index{testing!knowing the answer}46224623At this point we have confirmed that the function is syntactically4624correct, and we can start adding code to the body.4625A reasonable next step is to find the differences4626$x_2 - x_1$ and $y_2 - y_1$. The next version stores those values in4627temporary variables and prints them.46284629\begin{verbatim}4630def distance(x1, y1, x2, y2):4631dx = x2 - x14632dy = y2 - y14633print('dx is', dx)4634print('dy is', dy)4635return 0.04636\end{verbatim}4637%4638If the function is working, it should display \verb"dx is 3" and4639\verb"dy is 4". If so, we know that the function is getting the right4640arguments and performing the first computation correctly. If not,4641there are only a few lines to check.46424643Next we compute the sum of squares of {\tt dx} and {\tt dy}:46444645\begin{verbatim}4646def distance(x1, y1, x2, y2):4647dx = x2 - x14648dy = y2 - y14649dsquared = dx**2 + dy**24650print('dsquared is: ', dsquared)4651return 0.04652\end{verbatim}4653%4654Again, you would run the program at this stage and check the output4655(which should be 25).4656Finally, you can use {\tt math.sqrt} to compute and return the result:4657\index{sqrt}4658\index{function!sqrt}46594660\begin{verbatim}4661def distance(x1, y1, x2, y2):4662dx = x2 - x14663dy = y2 - y14664dsquared = dx**2 + dy**24665result = math.sqrt(dsquared)4666return result4667\end{verbatim}4668%4669If that works correctly, you are done. Otherwise, you might4670want to print the value of {\tt result} before the return4671statement.46724673The final version of the function doesn't display anything when it4674runs; it only returns a value. The {\tt print} statements we wrote4675are useful for debugging, but once you get the function working, you4676should remove them. Code like that is called {\bf scaffolding}4677because it is helpful for building the program but is not part of the4678final product.4679\index{scaffolding}46804681When you start out, you should add only a line or two of code at a4682time. As you gain more experience, you might find yourself writing4683and debugging bigger chunks. Either way, incremental development4684can save you a lot of debugging time.46854686The key aspects of the process are:46874688\begin{enumerate}46894690\item Start with a working program and make small incremental changes.4691At any point, if there is an error, you should have a good idea4692where it is.46934694\item Use variables to hold intermediate values so you can4695display and check them.46964697\item Once the program is working, you might want to remove some of4698the scaffolding or consolidate multiple statements into compound4699expressions, but only if it does not make the program difficult to4700read.47014702\end{enumerate}47034704As an exercise, use incremental development to write a function4705called {\tt hypotenuse} that returns the length of the hypotenuse of a4706right triangle given the lengths of the other two legs as arguments.4707Record each stage of the development process as you go.4708\index{hypotenuse}4709471047114712\section{Composition}4713\index{composition}4714\index{function composition}47154716As you should expect by now, you can call one function from within4717another. As an example, we'll write a function that takes two points,4718the center of the circle and a point on the perimeter, and computes4719the area of the circle.47204721Assume that the center point is stored in the variables {\tt xc} and4722{\tt yc}, and the perimeter point is in {\tt xp} and {\tt yp}. The4723first step is to find the radius of the circle, which is the distance4724between the two points. We just wrote a function, {\tt4725distance}, that does that:47264727\begin{verbatim}4728radius = distance(xc, yc, xp, yp)4729\end{verbatim}4730%4731The next step is to find the area of a circle with that radius;4732we just wrote that, too:47334734\begin{verbatim}4735result = area(radius)4736\end{verbatim}4737%4738Encapsulating these steps in a function, we get:4739\index{encapsulation}47404741\begin{verbatim}4742def circle_area(xc, yc, xp, yp):4743radius = distance(xc, yc, xp, yp)4744result = area(radius)4745return result4746\end{verbatim}4747%4748The temporary variables {\tt radius} and {\tt result} are useful for4749development and debugging, but once the program is working, we can4750make it more concise by composing the function calls:47514752\begin{verbatim}4753def circle_area(xc, yc, xp, yp):4754return area(distance(xc, yc, xp, yp))4755\end{verbatim}4756%47574758\section{Boolean functions}4759\label{boolean}47604761Functions can return booleans, which is often convenient for hiding4762complicated tests inside functions. \index{boolean function}4763For example:47644765\begin{verbatim}4766def is_divisible(x, y):4767if x % y == 0:4768return True4769else:4770return False4771\end{verbatim}4772%4773It is common to give boolean functions names that sound like yes/no4774questions; \verb"is_divisible" returns either {\tt True} or {\tt False}4775to indicate whether {\tt x} is divisible by {\tt y}.47764777Here is an example:47784779\begin{verbatim}4780>>> is_divisible(6, 4)4781False4782>>> is_divisible(6, 3)4783True4784\end{verbatim}4785%4786The result of the {\tt ==} operator is a boolean, so we can write the4787function more concisely by returning it directly:47884789\begin{verbatim}4790def is_divisible(x, y):4791return x % y == 04792\end{verbatim}4793%4794Boolean functions are often used in conditional statements:4795\index{conditional statement}4796\index{statement!conditional}47974798\begin{verbatim}4799if is_divisible(x, y):4800print('x is divisible by y')4801\end{verbatim}4802%4803It might be tempting to write something like:48044805\begin{verbatim}4806if is_divisible(x, y) == True:4807print('x is divisible by y')4808\end{verbatim}4809%4810But the extra comparison is unnecessary.48114812As an exercise, write a function \verb"is_between(x, y, z)" that4813returns {\tt True} if $x \le y \le z$ or {\tt False} otherwise.481448154816\section{More recursion}4817\label{more.recursion}4818\index{recursion}4819\index{Turing complete language}4820\index{language!Turing complete}4821\index{Turing, Alan}4822\index{Turing Thesis}48234824We have only covered a small subset of Python, but you might4825be interested to know that this subset is a {\em complete}4826programming language, which means that anything that can be4827computed can be expressed in this language. Any program ever written4828could be rewritten using only the language features you have learned4829so far (actually, you would need a few commands to control devices4830like the mouse, disks, etc., but that's all).48314832Proving that claim is a nontrivial exercise first accomplished by Alan4833Turing, one of the first computer scientists (some would argue that he4834was a mathematician, but a lot of early computer scientists started as4835mathematicians). Accordingly, it is known as the Turing Thesis.4836For a more complete (and accurate) discussion of the Turing Thesis,4837I recommend Michael Sipser's book {\em Introduction to the4838Theory of Computation}.48394840To give you an idea of what you can do with the tools you have learned4841so far, we'll evaluate a few recursively defined mathematical4842functions. A recursive definition is similar to a circular4843definition, in the sense that the definition contains a reference to4844the thing being defined. A truly circular definition is not very4845useful:48464847\begin{description}48484849\item[vorpal:] An adjective used to describe something that is vorpal.4850\index{vorpal}4851\index{circular definition}4852\index{definition!circular}48534854\end{description}48554856If you saw that definition in the dictionary, you might be annoyed. On4857the other hand, if you looked up the definition of the factorial4858function, denoted with the symbol $!$, you might get something like4859this:4860%4861\begin{eqnarray*}4862&& 0! = 1 \\4863&& n! = n (n-1)!4864\end{eqnarray*}4865%4866This definition says that the factorial of 0 is 1, and the factorial4867of any other value, $n$, is $n$ multiplied by the factorial of $n-1$.48684869So $3!$ is 3 times $2!$, which is 2 times $1!$, which is 1 times4870$0!$. Putting it all together, $3!$ equals 3 times 2 times 1 times 1,4871which is 6.4872\index{factorial function}4873\index{function!factorial}4874\index{recursive definition}48754876If you can write a recursive definition of something, you can4877write a Python program to evaluate it. The first step is to decide4878what the parameters should be. In this case it should be clear4879that {\tt factorial} takes an integer:48804881\begin{verbatim}4882def factorial(n):4883\end{verbatim}4884%4885If the argument happens to be 0, all we have to do is return 1:48864887\begin{verbatim}4888def factorial(n):4889if n == 0:4890return 14891\end{verbatim}4892%4893Otherwise, and this is the interesting part, we have to make a4894recursive call to find the factorial of $n-1$ and then multiply it by4895$n$:48964897\begin{verbatim}4898def factorial(n):4899if n == 0:4900return 14901else:4902recurse = factorial(n-1)4903result = n * recurse4904return result4905\end{verbatim}4906%4907The flow of execution for this program is similar to the flow of {\tt4908countdown} in Section~\ref{recursion}. If we call {\tt factorial}4909with the value 3:49104911Since 3 is not 0, we take the second branch and calculate the factorial4912of {\tt n-1}...49134914\begin{quote}4915Since 2 is not 0, we take the second branch and calculate the factorial of4916{\tt n-1}...491749184919\begin{quote}4920Since 1 is not 0, we take the second branch and calculate the factorial4921of {\tt n-1}...492249234924\begin{quote}4925Since 0 equals 0, we take the first branch and return 14926without making any more recursive calls.4927\end{quote}492849294930The return value, 1, is multiplied by $n$, which is 1, and the4931result is returned.4932\end{quote}493349344935The return value, 1, is multiplied by $n$, which is 2, and the4936result is returned.4937\end{quote}493849394940The return value (2) is multiplied by $n$, which is 3, and the result, 6,4941becomes the return value of the function call that started the whole4942process.4943\index{stack diagram}49444945Figure~\ref{fig.stack3} shows what the stack diagram looks like for4946this sequence of function calls.49474948\begin{figure}4949\centerline4950{\includegraphics[scale=0.8]{figs/stack3.pdf}}4951\caption{Stack diagram.}4952\label{fig.stack3}4953\end{figure}49544955The return values are shown being passed back up the stack. In each4956frame, the return value is the value of {\tt result}, which is the4957product of {\tt n} and {\tt recurse}.4958\index{function frame}4959\index{frame}49604961In the last frame, the local4962variables {\tt recurse} and {\tt result} do not exist, because4963the branch that creates them does not run.496449654966\section{Leap of faith}4967\index{recursion}4968\index{leap of faith}49694970Following the flow of execution is one way to read programs, but4971it can quickly become overwhelming. An4972alternative is what I call the ``leap of faith''. When you come to a4973function call, instead of following the flow of execution, you {\em4974assume} that the function works correctly and returns the right4975result.49764977In fact, you are already practicing this leap of faith when you use4978built-in functions. When you call {\tt math.cos} or {\tt math.exp},4979you don't examine the bodies of those functions. You just4980assume that they work because the people who wrote the built-in4981functions were good programmers.49824983The same is true when you call one of your own functions. For4984example, in Section~\ref{boolean}, we wrote a function called4985\verb"is_divisible" that determines whether one number is divisible by4986another. Once we have convinced ourselves that this function is4987correct---by examining the code and testing---we can use the function4988without looking at the body again.4989\index{testing!leap of faith}49904991The same is true of recursive programs. When you get to the recursive4992call, instead of following the flow of execution, you should assume4993that the recursive call works (returns the correct result) and then ask4994yourself, ``Assuming that I can find the factorial of $n-1$, can I4995compute the factorial of $n$?'' It is clear that you4996can, by multiplying by $n$.49974998Of course, it's a bit strange to assume that the function works4999correctly when you haven't finished writing it, but that's why5000it's called a leap of faith!500150025003\section{One more example}5004\label{one.more.example}50055006\index{fibonacci function}5007\index{function!fibonacci}5008After {\tt factorial}, the most common example of a recursively5009defined mathematical function is {\tt fibonacci}, which has the5010following definition (see5011\url{http://en.wikipedia.org/wiki/Fibonacci_number}):5012%5013\begin{eqnarray*}5014&& \mathrm{fibonacci}(0) = 0 \\5015&& \mathrm{fibonacci}(1) = 1 \\5016&& \mathrm{fibonacci}(n) = \mathrm{fibonacci}(n-1) + \mathrm{fibonacci}(n-2)5017\end{eqnarray*}5018%5019Translated into Python, it looks like this:50205021\begin{verbatim}5022def fibonacci(n):5023if n == 0:5024return 05025elif n == 1:5026return 15027else:5028return fibonacci(n-1) + fibonacci(n-2)5029\end{verbatim}5030%5031If you try to follow the flow of execution here, even for fairly5032small values of $n$, your head explodes. But according to the5033leap of faith, if you assume that the two recursive calls5034work correctly, then it is clear that you get5035the right result by adding them together.5036\index{flow of execution}503750385039\section{Checking types}5040\label{guardian}50415042What happens if we call {\tt factorial} and give it 1.5 as an argument?5043\index{type checking}5044\index{error checking}5045\index{factorial function}5046\index{RuntimeError}50475048\begin{verbatim}5049>>> factorial(1.5)5050RuntimeError: Maximum recursion depth exceeded5051\end{verbatim}5052%5053It looks like an infinite recursion. How can that be? The function5054has a base case---when {\tt n == 0}. But if {\tt n} is not an integer,5055we can {\em miss} the base case and recurse forever.5056\index{infinite recursion}5057\index{recursion!infinite}50585059In the first recursive call, the value of {\tt n} is 0.5.5060In the next, it is -0.5. From there, it gets smaller5061(more negative), but it will never be 0.50625063We have two choices. We can try to generalize the {\tt factorial}5064function to work with floating-point numbers, or we can make {\tt5065factorial} check the type of its argument. The first option is5066called the gamma function and it's a5067little beyond the scope of this book. So we'll go for the second.5068\index{gamma function}50695070We can use the built-in function {\tt isinstance} to verify the type5071of the argument. While we're at it, we can also make sure the5072argument is positive:5073\index{isinstance function}5074\index{function!isinstance}50755076\begin{verbatim}5077def factorial(n):5078if not isinstance(n, int):5079print('Factorial is only defined for integers.')5080return None5081elif n < 0:5082print('Factorial is not defined for negative integers.')5083return None5084elif n == 0:5085return 15086else:5087return n * factorial(n-1)5088\end{verbatim}5089%5090The first base case handles nonintegers; the5091second handles negative integers. In both cases, the program prints5092an error message and returns {\tt None} to indicate that something5093went wrong:50945095\begin{verbatim}5096>>> print(factorial('fred'))5097Factorial is only defined for integers.5098None5099>>> print(factorial(-2))5100Factorial is not defined for negative integers.5101None5102\end{verbatim}5103%5104If we get past both checks, we know that $n$ is a non-negative integer, so we can prove that the recursion terminates.5105\index{guardian pattern}5106\index{pattern!guardian}51075108This program demonstrates a pattern sometimes called a {\bf guardian}.5109The first two conditionals act as guardians, protecting the code that5110follows from values that might cause an error. The guardians make it5111possible to prove the correctness of the code.51125113In Section~\ref{raise} we will see a more flexible alternative to printing5114an error message: raising an exception.511551165117\section{Debugging}5118\label{factdebug}51195120Breaking a large program into smaller functions creates natural5121checkpoints for debugging. If a function is not5122working, there are three possibilities to consider:5123\index{debugging}51245125\begin{itemize}51265127\item There is something wrong with the arguments the function5128is getting; a precondition is violated.51295130\item There is something wrong with the function; a postcondition5131is violated.51325133\item There is something wrong with the return value or the5134way it is being used.51355136\end{itemize}51375138To rule out the first possibility, you can add a {\tt print} statement5139at the beginning of the function and display the values of the5140parameters (and maybe their types). Or you can write code5141that checks the preconditions explicitly.5142\index{precondition}5143\index{postcondition}51445145If the parameters look good, add a {\tt print} statement before each5146{\tt return} statement and display the return value. If5147possible, check the result by hand. Consider calling the5148function with values that make it easy to check the result5149(as in Section~\ref{incremental.development}).51505151If the function seems to be working, look at the function call5152to make sure the return value is being used correctly (or used5153at all!).5154\index{flow of execution}51555156Adding print statements at the beginning and end of a function5157can help make the flow of execution more visible.5158For example, here is a version of {\tt factorial} with5159print statements:51605161\begin{verbatim}5162def factorial(n):5163space = ' ' * (4 * n)5164print(space, 'factorial', n)5165if n == 0:5166print(space, 'returning 1')5167return 15168else:5169recurse = factorial(n-1)5170result = n * recurse5171print(space, 'returning', result)5172return result5173\end{verbatim}5174%5175{\tt space} is a string of space characters that controls the5176indentation of the output. Here is the result of {\tt factorial(4)} :51775178\begin{verbatim}5179factorial 45180factorial 35181factorial 25182factorial 15183factorial 05184returning 15185returning 15186returning 25187returning 65188returning 245189\end{verbatim}5190%5191If you are confused about the flow of execution, this kind of5192output can be helpful. It takes some time to develop effective5193scaffolding, but a little bit of scaffolding can save a lot of debugging.519451955196\section{Glossary}51975198\begin{description}51995200\item[temporary variable:] A variable used to store an intermediate value in5201a complex calculation.5202\index{temporary variable}5203\index{variable!temporary}52045205\item[dead code:] Part of a program that can never run, often because5206it appears after a {\tt return} statement.5207\index{dead code}52085209\item[incremental development:] A program development plan intended to5210avoid debugging by adding and testing only5211a small amount of code at a time.5212\index{incremental development}52135214\item[scaffolding:] Code that is used during program development but is5215not part of the final version.5216\index{scaffolding}52175218\item[guardian:] A programming pattern that uses a conditional5219statement to check for and handle circumstances that5220might cause an error.5221\index{guardian pattern}5222\index{pattern!guardian}52235224\end{description}522552265227\section{Exercises}52285229\begin{exercise}52305231Draw a stack diagram for the following program. What does the program print?5232\index{stack diagram}52335234\begin{verbatim}5235def b(z):5236prod = a(z, z)5237print(z, prod)5238return prod52395240def a(x, y):5241x = x + 15242return x * y52435244def c(x, y, z):5245total = x + y + z5246square = b(total)**25247return square52485249x = 15250y = x + 15251print(c(x, y+3, x+y))5252\end{verbatim}52535254\end{exercise}525552565257\begin{exercise}5258\label{ackermann}52595260The Ackermann function, $A(m, n)$, is defined:52615262\begin{eqnarray*}5263A(m, n) = \begin{cases}5264n+1 & \mbox{if } m = 0 \\5265A(m-1, 1) & \mbox{if } m > 0 \mbox{ and } n = 0 \\5266A(m-1, A(m, n-1)) & \mbox{if } m > 0 \mbox{ and } n > 0.5267\end{cases}5268\end{eqnarray*}5269%5270See \url{http://en.wikipedia.org/wiki/Ackermann_function}.5271Write a function named {\tt ack} that evaluates the Ackermann function.5272Use your function to evaluate {\tt ack(3, 4)}, which should be 125.5273What happens for larger values of {\tt m} and {\tt n}?5274Solution: \url{http://thinkpython2.com/code/ackermann.py}.5275\index{Ackermann function}5276\index{function!ack}52775278\end{exercise}527952805281\begin{exercise}5282\label{palindrome}52835284A palindrome is a word that is spelled the same backward and5285forward, like ``noon'' and ``redivider''. Recursively, a word5286is a palindrome if the first and last letters are the same5287and the middle is a palindrome.5288\index{palindrome}52895290The following are functions that take a string argument and5291return the first, last, and middle letters:52925293\begin{verbatim}5294def first(word):5295return word[0]52965297def last(word):5298return word[-1]52995300def middle(word):5301return word[1:-1]5302\end{verbatim}5303%5304We'll see how they work in Chapter~\ref{strings}.53055306\begin{enumerate}53075308\item Type these functions into a file named {\tt palindrome.py}5309and test them out. What happens if you call {\tt middle} with5310a string with two letters? One letter? What about the empty5311string, which is written \verb"''" and contains no letters?53125313\item Write a function called \verb"is_palindrome" that takes5314a string argument and returns {\tt True} if it is a palindrome5315and {\tt False} otherwise. Remember that you can use the5316built-in function {\tt len} to check the length of a string.53175318\end{enumerate}53195320Solution: \url{http://thinkpython2.com/code/palindrome_soln.py}.53215322\end{exercise}53235324\begin{exercise}53255326A number, $a$, is a power of $b$ if it is divisible by $b$5327and $a/b$ is a power of $b$. Write a function called5328\verb"is_power" that takes parameters {\tt a} and {\tt b}5329and returns {\tt True} if {\tt a} is a power of {\tt b}.5330Note: you will have to think about the base case.53315332\end{exercise}533353345335\begin{exercise}5336\index{greatest common divisor (GCD)}5337\index{GCD (greatest common divisor)}53385339The greatest common divisor (GCD) of $a$ and $b$ is the largest number5340that divides both of them with no remainder.53415342One way to find the GCD of two numbers is based on the observation5343that if $r$ is the remainder when $a$ is divided by $b$, then $gcd(a,5344b) = gcd(b, r)$. As a base case, we can use $gcd(a, 0) = a$.53455346Write a function called5347\verb"gcd" that takes parameters {\tt a} and {\tt b}5348and returns their greatest common divisor.53495350Credit: This exercise is based on an example from Abelson and5351Sussman's {\em Structure and Interpretation of Computer Programs}.53525353\end{exercise}535453555356\chapter{Iteration}53575358This chapter is about iteration, which is the ability to run5359a block of statements repeatedly. We saw a kind of iteration,5360using recursion, in Section~\ref{recursion}.5361We saw another kind, using a {\tt for} loop,5362in Section~\ref{repetition}. In this chapter we'll see yet another5363kind, using a {\tt while} statement.5364But first I want to say a little more about variable assignment.536553665367\section{Reassignment}5368\index{assignment}5369\index{statement!assignment}5370\index{reassignment}53715372As you may have discovered, it is legal to make more than one5373assignment to the same variable. A new assignment makes an existing5374variable refer to a new value (and stop referring to the old value).53755376\begin{verbatim}5377>>> x = 55378>>> x537955380>>> x = 75381>>> x538275383\end{verbatim}5384%5385The first time we display5386{\tt x}, its value is 5; the second time, its5387value is 7.53885389Figure~\ref{fig.assign2} shows what {\bf reassignment} looks5390like in a state diagram. \index{state diagram} \index{diagram!state}53915392At this point I want to address a common source of5393confusion.5394Because Python uses the equal sign ({\tt =}) for assignment, it is5395tempting to interpret a statement like {\tt a = b} as a5396mathematical5397proposition of equality; that is, the claim that {\tt a} and5398{\tt b} are equal. But this interpretation is wrong.5399\index{equality and assignment}54005401First, equality is a symmetric relationship and assignment is not. For5402example, in mathematics, if $a=7$ then $7=a$. But in Python, the5403statement {\tt a = 7} is legal and {\tt 7 = a} is not.54045405Also, in mathematics, a proposition of equality is either true or5406false for all time. If $a=b$ now, then $a$ will always equal $b$.5407In Python, an assignment statement can make two variables equal, but5408they don't have to stay that way:54095410\begin{verbatim}5411>>> a = 55412>>> b = a # a and b are now equal5413>>> a = 3 # a and b are no longer equal5414>>> b541555416\end{verbatim}5417%5418The third line changes the value of {\tt a} but does not change the5419value of {\tt b}, so they are no longer equal.54205421Reassigning variables is often useful, but you should use it5422with caution. If the values of variables change frequently, it can5423make the code difficult to read and debug.54245425\begin{figure}5426\centerline5427{\includegraphics[scale=0.8]{figs/assign2.pdf}}5428\caption{State diagram.}5429\label{fig.assign2}5430\end{figure}5431543254335434\section{Updating variables}5435\label{update}54365437\index{update}5438\index{variable!updating}54395440A common kind of reassignment is an {\bf update},5441where the new value of the variable depends on the old.54425443\begin{verbatim}5444>>> x = x + 15445\end{verbatim}5446%5447This means ``get the current value of {\tt x}, add one, and then5448update {\tt x} with the new value.''54495450If you try to update a variable that doesn't exist, you get an5451error, because Python evaluates the right side before it assigns5452a value to {\tt x}:54535454\begin{verbatim}5455>>> x = x + 15456NameError: name 'x' is not defined5457\end{verbatim}5458%5459Before you can update a variable, you have to {\bf initialize}5460it, usually with a simple assignment:5461\index{initialization (before update)}54625463\begin{verbatim}5464>>> x = 05465>>> x = x + 15466\end{verbatim}5467%5468Updating a variable by adding 1 is called an {\bf increment};5469subtracting 1 is called a {\bf decrement}.5470\index{increment}5471\index{decrement}54725473547454755476\section{The {\tt while} statement}5477\index{statement!while}5478\index{while loop}5479\index{loop!while}5480\index{iteration}54815482Computers are often used to automate repetitive tasks. Repeating5483identical or similar tasks without making errors is something that5484computers do well and people do poorly. In a computer program,5485repetition is also called {\bf iteration}.54865487We have already seen two functions, {\tt countdown} and5488\verb"print_n", that iterate using recursion. Because iteration is so5489common, Python provides language features to make it easier.5490One is the {\tt for} statement we saw in Section~\ref{repetition}.5491We'll get back to that later.54925493Another is the {\tt while} statement. Here is a version of {\tt5494countdown} that uses a {\tt while} statement:54955496\begin{verbatim}5497def countdown(n):5498while n > 0:5499print(n)5500n = n - 15501print('Blastoff!')5502\end{verbatim}5503%5504You can almost read the {\tt while} statement as if it were English.5505It means, ``While {\tt n} is greater than 0,5506display the value of {\tt n} and then decrement5507{\tt n}. When you get to 0, display the word {\tt Blastoff!}''5508\index{flow of execution}55095510More formally, here is the flow of execution for a {\tt while} statement:55115512\begin{enumerate}55135514\item Determine whether the condition is true or false.55155516\item If false, exit the {\tt while} statement5517and continue execution at the next statement.55185519\item If the condition is true, run the5520body and then go back to step 1.55215522\end{enumerate}55235524This type of flow is called a loop because the third step5525loops back around to the top.5526\index{condition}5527\index{loop}5528\index{body}55295530The body of the loop should change the value of one or more variables5531so that the condition becomes false eventually and the loop5532terminates. Otherwise the loop will repeat forever, which is called5533an {\bf infinite loop}. An endless source of amusement for computer5534scientists is the observation that the directions on shampoo,5535``Lather, rinse, repeat'', are an infinite loop.5536\index{infinite loop}5537\index{loop!infinite}55385539In the case of {\tt countdown}, we can prove that the loop5540terminates: if {\tt n} is zero or negative, the loop never runs.5541Otherwise, {\tt n} gets smaller each time through the5542loop, so eventually we have to get to 0.55435544For some other loops, it is not so easy to tell. For example:55455546\begin{verbatim}5547def sequence(n):5548while n != 1:5549print(n)5550if n % 2 == 0: # n is even5551n = n / 25552else: # n is odd5553n = n*3 + 15554\end{verbatim}5555%5556The condition for this loop is {\tt n != 1}, so the loop will continue5557until {\tt n} is {\tt 1}, which makes the condition false.55585559Each time through the loop, the program outputs the value of {\tt n}5560and then checks whether it is even or odd. If it is even, {\tt n} is5561divided by 2. If it is odd, the value of {\tt n} is replaced with5562{\tt n*3 + 1}. For example, if the argument passed to {\tt sequence}5563is 3, the resulting values of {\tt n} are 3, 10, 5, 16, 8, 4, 2, 1.55645565Since {\tt n} sometimes increases and sometimes decreases, there is no5566obvious proof that {\tt n} will ever reach 1, or that the program5567terminates. For some particular values of {\tt n}, we can prove5568termination. For example, if the starting value is a power of two,5569{\tt n} will be even every time through the loop5570until it reaches 1. The previous example ends with such a sequence,5571starting with 16.5572\index{Collatz conjecture}55735574The hard question is whether we can prove that this program terminates5575for {\em all} positive values of {\tt n}. So far, no one has5576been able to prove it {\em or} disprove it! (See5577\url{http://en.wikipedia.org/wiki/Collatz_conjecture}.)55785579As an exercise, rewrite the function \verb"print_n" from5580Section~\ref{recursion} using iteration instead of recursion.558155825583\section{{\tt break}}5584\index{break statement}5585\index{statement!break}55865587Sometimes you don't know it's time to end a loop until you get half5588way through the body. In that case you can use the {\tt break}5589statement to jump out of the loop.55905591For example, suppose you want to take input from the user until they5592type {\tt done}. You could write:55935594\begin{verbatim}5595while True:5596line = input('> ')5597if line == 'done':5598break5599print(line)56005601print('Done!')5602\end{verbatim}5603%5604The loop condition is {\tt True}, which is always true, so the5605loop runs until it hits the break statement.56065607Each time through, it prompts the user with an angle bracket.5608If the user types {\tt done}, the {\tt break} statement exits5609the loop. Otherwise the program echoes whatever the user types5610and goes back to the top of the loop. Here's a sample run:56115612\begin{verbatim}5613> not done5614not done5615> done5616Done!5617\end{verbatim}5618%5619This way of writing {\tt while} loops is common because you5620can check the condition anywhere in the loop (not just at the5621top) and you can express the stop condition affirmatively5622(``stop when this happens'') rather than negatively (``keep going5623until that happens'').562456255626\section{Square roots}5627\label{squareroot}5628\index{square root}56295630Loops are often used in programs that compute5631numerical results by starting with an approximate answer and5632iteratively improving it.5633\index{Newton's method}56345635For example, one way of computing square roots is Newton's method.5636Suppose that you want to know the square root of $a$. If you start5637with almost any estimate, $x$, you can compute a better5638estimate with the following formula:56395640\[ y = \frac{x + a/x}{2} \]5641%5642For example, if $a$ is 4 and $x$ is 3:56435644\begin{verbatim}5645>>> a = 45646>>> x = 35647>>> y = (x + a/x) / 25648>>> y56492.166666666675650\end{verbatim}5651%5652The result is closer to the correct answer ($\sqrt{4} = 2$). If we5653repeat the process with the new estimate, it gets even closer:56545655\begin{verbatim}5656>>> x = y5657>>> y = (x + a/x) / 25658>>> y56592.006410256415660\end{verbatim}5661%5662After a few more updates, the estimate is almost exact:5663\index{update}56645665\begin{verbatim}5666>>> x = y5667>>> y = (x + a/x) / 25668>>> y56692.000010240035670>>> x = y5671>>> y = (x + a/x) / 25672>>> y56732.000000000035674\end{verbatim}5675%5676In general we don't know ahead of time how many steps it takes5677to get to the right answer, but we know when we get there5678because the estimate5679stops changing:56805681\begin{verbatim}5682>>> x = y5683>>> y = (x + a/x) / 25684>>> y56852.05686>>> x = y5687>>> y = (x + a/x) / 25688>>> y56892.05690\end{verbatim}5691%5692When {\tt y == x}, we can stop. Here is a loop that starts5693with an initial estimate, {\tt x}, and improves it until it5694stops changing:56955696\begin{verbatim}5697while True:5698print(x)5699y = (x + a/x) / 25700if y == x:5701break5702x = y5703\end{verbatim}5704%5705For most values of {\tt a} this works fine, but in general it is5706dangerous to test {\tt float} equality.5707Floating-point values are only approximately right:5708most rational numbers, like $1/3$, and irrational numbers, like5709$\sqrt{2}$, can't be represented exactly with a {\tt float}.5710\index{floating-point}5711\index{epsilon}57125713Rather than checking whether {\tt x} and {\tt y} are exactly equal, it5714is safer to use the built-in function {\tt abs} to compute the5715absolute value, or magnitude, of the difference between them:57165717\begin{verbatim}5718if abs(y-x) < epsilon:5719break5720\end{verbatim}5721%5722Where \verb"epsilon" has a value like {\tt 0.0000001} that5723determines how close is close enough.572457255726\section{Algorithms}5727\index{algorithm}57285729Newton's method is an example of an {\bf algorithm}: it is a5730mechanical process for solving a category of problems (in this5731case, computing square roots).57325733To understand what an algorithm is, it might help to start with5734something that is not an algorithm. When you learned to multiply5735single-digit numbers, you probably memorized the multiplication table.5736In effect, you memorized 100 specific solutions. That kind of5737knowledge is not algorithmic.57385739But if you were ``lazy'', you might have learned a few5740tricks. For example, to find the product of $n$ and 9, you can5741write $n-1$ as the first digit and $10-n$ as the second5742digit. This trick is a general solution for multiplying any5743single-digit number by 9. That's an algorithm!5744\index{addition with carrying}5745\index{carrying, addition with}5746\index{subtraction!with borrowing}5747\index{borrowing, subtraction with}57485749Similarly, the techniques you learned for addition with carrying,5750subtraction with borrowing, and long division are all algorithms. One5751of the characteristics of algorithms is that they do not require any5752intelligence to carry out. They are mechanical processes where5753each step follows from the last according to a simple set of rules.57545755Executing algorithms is boring, but designing them is interesting,5756intellectually challenging, and a central part of computer science.57575758Some of the things that people do naturally, without difficulty or5759conscious thought, are the hardest to express algorithmically.5760Understanding natural language is a good example. We all do it, but5761so far no one has been able to explain {\em how} we do it, at least5762not in the form of an algorithm.576357645765\section{Debugging}5766\label{bisectbug}57675768As you start writing bigger programs, you might find yourself5769spending more time debugging. More code means more chances to5770make an error and more places for bugs to hide.5771\index{debugging!by bisection}5772\index{bisection, debugging by}57735774One way to cut your debugging time is ``debugging by bisection''.5775For example, if there are 100 lines in your program and you5776check them one at a time, it would take 100 steps.57775778Instead, try to break the problem in half. Look at the middle5779of the program, or near it, for an intermediate value you5780can check. Add a {\tt print} statement (or something else5781that has a verifiable effect) and run the program.57825783If the mid-point check is incorrect, there must be a problem in the5784first half of the program. If it is correct, the problem is5785in the second half.57865787Every time you perform a check like this, you halve the number of5788lines you have to search. After six steps (which is fewer than 100),5789you would be down to one or two lines of code, at least in theory.57905791In practice it is not always clear what5792the ``middle of the program'' is and not always possible to5793check it. It doesn't make sense to count lines and find the5794exact midpoint. Instead, think about places5795in the program where there might be errors and places where it5796is easy to put a check. Then choose a spot where you5797think the chances are about the same that the bug is before5798or after the check.57995800580158025803\section{Glossary}58045805\begin{description}58065807\item[reassignment:] Assigning a new value to a variable that5808already exists.5809\index{reassignment}58105811\item[update:] An assignment where the new value of the variable5812depends on the old.5813\index{update}58145815\item[initialization:] An assignment that gives an initial value to5816a variable that will be updated.5817\index{initialization!variable}58185819\item[increment:] An update that increases the value of a variable5820(often by one).5821\index{increment}58225823\item[decrement:] An update that decreases the value of a variable.5824\index{decrement}58255826\item[iteration:] Repeated execution of a set of statements using5827either a recursive function call or a loop.5828\index{iteration}58295830\item[infinite loop:] A loop in which the terminating condition is5831never satisfied.5832\index{infinite loop}58335834\item[algorithm:] A general process for solving a category of5835problems.5836\index{algorithm}58375838\end{description}583958405841\section{Exercises}58425843\begin{exercise}5844\index{algorithm!square root}58455846Copy the loop from Section~\ref{squareroot}5847and encapsulate it in a function called5848\verb"mysqrt" that takes {\tt a} as a parameter, chooses a5849reasonable value of {\tt x}, and returns an estimate of the square5850root of {\tt a}. \index{encapsulation}58515852To test it, write a function named \verb"test_square_root"5853that prints a table like this:58545855\begin{verbatim}5856a mysqrt(a) math.sqrt(a) diff5857- --------- ------------ ----58581.0 1.0 1.0 0.058592.0 1.41421356237 1.41421356237 2.22044604925e-1658603.0 1.73205080757 1.73205080757 0.058614.0 2.0 2.0 0.058625.0 2.2360679775 2.2360679775 0.058636.0 2.44948974278 2.44948974278 0.058647.0 2.64575131106 2.64575131106 0.058658.0 2.82842712475 2.82842712475 4.4408920985e-1658669.0 3.0 3.0 0.05867\end{verbatim}5868%5869The first column is a number, $a$; the second column is the square5870root of $a$ computed with \verb"mysqrt"; the third column is the5871square root computed by {\tt math.sqrt}; the fourth column is the5872absolute value of the difference between the two estimates.5873\end{exercise}587458755876\begin{exercise}5877\index{eval function}5878\index{function!eval}58795880The built-in function {\tt eval} takes a string and evaluates5881it using the Python interpreter. For example:58825883\begin{verbatim}5884>>> eval('1 + 2 * 3')588575886>>> import math5887>>> eval('math.sqrt(5)')58882.23606797749978985889>>> eval('type(math.pi)')5890<class 'float'>5891\end{verbatim}5892%5893Write a function called \verb"eval_loop" that iteratively5894prompts the user, takes the resulting input and evaluates5895it using {\tt eval}, and prints the result.58965897It should continue until the user enters \verb"'done'", and then5898return the value of the last expression it evaluated.58995900\end{exercise}590159025903\begin{exercise}5904\index{Ramanujan, Srinivasa}59055906The mathematician Srinivasa Ramanujan found an5907infinite series5908that can be used to generate a numerical5909approximation of $1 / \pi$:5910\index{pi}59115912\[ \frac{1}{\pi} = \frac{2\sqrt{2}}{9801}5913\sum^\infty_{k=0} \frac{(4k)!(1103+26390k)}{(k!)^4 396^{4k}} \]59145915Write a function called \verb"estimate_pi" that uses this formula5916to compute and return an estimate of $\pi$. It should use a {\tt while}5917loop to compute terms of the summation until the last term is5918smaller than {\tt 1e-15} (which is Python notation for $10^{-15}$).5919You can check the result by comparing it to {\tt math.pi}.59205921Solution: \url{http://thinkpython2.com/code/pi.py}.59225923\end{exercise}592459255926\chapter{Strings}5927\label{strings}59285929Strings are not like integers, floats, and booleans. A string5930is a {\bf sequence}, which means it is5931an ordered collection of other values. In this chapter you'll see5932how to access the characters that make up a string, and you'll5933learn about some of the methods strings provide.5934\index{sequence}593559365937\section{A string is a sequence}59385939\index{sequence}5940\index{character}5941\index{bracket operator}5942\index{operator!bracket}5943A string is a sequence of characters.5944You can access the characters one at a time with the5945bracket operator:59465947\begin{verbatim}5948>>> fruit = 'banana'5949>>> letter = fruit[1]5950\end{verbatim}5951%5952The second statement selects character number 1 from {\tt5953fruit} and assigns it to {\tt letter}.5954\index{index}59555956The expression in brackets is called an {\bf index}.5957The index indicates which character in the sequence you5958want (hence the name).59595960But you might not get what you expect:59615962\begin{verbatim}5963>>> letter5964'a'5965\end{verbatim}5966%5967For most people, the first letter of \verb"'banana'" is {\tt b}, not5968{\tt a}. But for computer scientists, the index is an offset from the5969beginning of the string, and the offset of the first letter is zero.59705971\begin{verbatim}5972>>> letter = fruit[0]5973>>> letter5974'b'5975\end{verbatim}5976%5977So {\tt b} is the 0th letter (``zero-eth'') of \verb"'banana'", {\tt5978a} is the 1th letter (``one-eth''), and {\tt n} is the 2th letter5979(``two-eth''). \index{index!starting at zero} \index{zero, index5980starting at}59815982As an index you can use an expression that contains variables and5983operators:5984\index{index}59855986\begin{verbatim}5987>>> i = 15988>>> fruit[i]5989'a'5990>>> fruit[i+1]5991'n'5992\end{verbatim}5993%59945995But the value of the index has to be an integer. Otherwise you5996get:5997\index{exception!TypeError}5998\index{TypeError}59996000\begin{verbatim}6001>>> letter = fruit[1.5]6002TypeError: string indices must be integers6003\end{verbatim}6004%60056006\section{{\tt len}}6007\index{len function}6008\index{function!len}60096010{\tt len} is a built-in function that returns the number of characters6011in a string:60126013\begin{verbatim}6014>>> fruit = 'banana'6015>>> len(fruit)601666017\end{verbatim}6018%6019To get the last letter of a string, you might be tempted to try something6020like this:6021\index{exception!IndexError}6022\index{IndexError}60236024\begin{verbatim}6025>>> length = len(fruit)6026>>> last = fruit[length]6027IndexError: string index out of range6028\end{verbatim}6029%6030The reason for the {\tt IndexError} is that there is no letter in {\tt6031'banana'} with the index 6. Since we started counting at zero, the6032six letters are numbered 0 to 5. To get the last character, you have6033to subtract 1 from {\tt length}:60346035\begin{verbatim}6036>>> last = fruit[length-1]6037>>> last6038'a'6039\end{verbatim}6040%6041Or you can use negative indices, which count backward from6042the end of the string. The expression {\tt fruit[-1]} yields the last6043letter, {\tt fruit[-2]} yields the second to last, and so on.6044\index{index!negative}6045\index{negative index}604660476048\section{Traversal with a {\tt for} loop}6049\label{for}6050\index{traversal}6051\index{loop!traversal}6052\index{for loop}6053\index{loop!for}6054\index{statement!for}6055\index{traversal}60566057A lot of computations involve processing a string one character at a6058time. Often they start at the beginning, select each character in6059turn, do something to it, and continue until the end. This pattern of6060processing is called a {\bf traversal}. One way to write a traversal6061is with a {\tt while} loop:60626063\begin{verbatim}6064index = 06065while index < len(fruit):6066letter = fruit[index]6067print(letter)6068index = index + 16069\end{verbatim}6070%6071This loop traverses the string and displays each letter on a line by6072itself. The loop condition is {\tt index < len(fruit)}, so6073when {\tt index} is equal to the length of the string, the6074condition is false, and the body of the loop doesn't run. The6075last character accessed is the one with the index {\tt len(fruit)-1},6076which is the last character in the string.60776078As an exercise, write a function that takes a string as an argument6079and displays the letters backward, one per line.60806081Another way to write a traversal is with a {\tt for} loop:60826083\begin{verbatim}6084for letter in fruit:6085print(letter)6086\end{verbatim}6087%6088Each time through the loop, the next character in the string is assigned6089to the variable {\tt letter}. The loop continues until no characters are6090left.6091\index{concatenation}6092\index{abecedarian}6093\index{McCloskey, Robert}60946095The following example shows how to use concatenation (string addition)6096and a {\tt for} loop to generate an abecedarian series (that is, in6097alphabetical order). In Robert McCloskey's book {\em Make6098Way for Ducklings}, the names of the ducklings are Jack, Kack, Lack,6099Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in6100order:61016102\begin{verbatim}6103prefixes = 'JKLMNOPQ'6104suffix = 'ack'61056106for letter in prefixes:6107print(letter + suffix)6108\end{verbatim}6109%6110The output is:61116112\begin{verbatim}6113Jack6114Kack6115Lack6116Mack6117Nack6118Oack6119Pack6120Qack6121\end{verbatim}6122%6123Of course, that's not quite right because ``Ouack'' and ``Quack'' are6124misspelled. As an exercise, modify the program to fix this error.6125612661276128\section{String slices}6129\label{slice}6130\index{slice operator} \index{operator!slice} \index{index!slice}6131\index{string!slice} \index{slice!string}61326133A segment of a string is called a {\bf slice}. Selecting a slice is6134similar to selecting a character:61356136\begin{verbatim}6137>>> s = 'Monty Python'6138>>> s[0:5]6139'Monty'6140>>> s[6:12]6141'Python'6142\end{verbatim}6143%6144The operator {\tt [n:m]} returns the part of the string from the6145``n-eth'' character to the ``m-eth'' character, including the first but6146excluding the last. This behavior is counterintuitive, but it might6147help to imagine the indices pointing {\em between} the6148characters, as in Figure~\ref{fig.banana}.61496150\begin{figure}6151\centerline6152{\includegraphics[scale=0.8]{figs/banana.pdf}}6153\caption{Slice indices.}6154\label{fig.banana}6155\end{figure}61566157If you omit the first index (before the colon), the slice starts at6158the beginning of the string. If you omit the second index, the slice6159goes to the end of the string:61606161\begin{verbatim}6162>>> fruit = 'banana'6163>>> fruit[:3]6164'ban'6165>>> fruit[3:]6166'ana'6167\end{verbatim}6168%6169If the first index is greater than or equal to the second the result6170is an {\bf empty string}, represented by two quotation marks:6171\index{quotation mark}61726173\begin{verbatim}6174>>> fruit = 'banana'6175>>> fruit[3:3]6176''6177\end{verbatim}6178%6179An empty string contains no characters and has length 0, but other6180than that, it is the same as any other string.61816182Continuing this example, what do you think6183{\tt fruit[:]} means? Try it and see.6184\index{copy!slice}6185\index{slice!copy}6186618761886189\section{Strings are immutable}6190\index{mutability}6191\index{immutability}6192\index{string!immutable}61936194It is tempting to use the {\tt []} operator on the left side of an6195assignment, with the intention of changing a character in a string.6196For example:6197\index{TypeError}6198\index{exception!TypeError}61996200\begin{verbatim}6201>>> greeting = 'Hello, world!'6202>>> greeting[0] = 'J'6203TypeError: 'str' object does not support item assignment6204\end{verbatim}6205%6206The ``object'' in this case is the string and the ``item'' is6207the character you tried to assign. For now, an object is6208the same thing as a value, but we will refine that definition6209later (Section~\ref{equivalence}).6210\index{object}6211\index{item}6212\index{item assignment}6213\index{assignment!item}6214\index{immutability}62156216The reason for the error is that6217strings are {\bf immutable}, which means you can't change an6218existing string. The best you can do is create a new string6219that is a variation on the original:62206221\begin{verbatim}6222>>> greeting = 'Hello, world!'6223>>> new_greeting = 'J' + greeting[1:]6224>>> new_greeting6225'Jello, world!'6226\end{verbatim}6227%6228This example concatenates a new first letter onto6229a slice of {\tt greeting}. It has no effect on6230the original string.6231\index{concatenation}623262336234\section{Searching}6235\label{find}62366237What does the following function do?6238\index{find function}6239\index{function!find}62406241\begin{verbatim}6242def find(word, letter):6243index = 06244while index < len(word):6245if word[index] == letter:6246return index6247index = index + 16248return -16249\end{verbatim}6250%6251In a sense, {\tt find} is the inverse of the {\tt []} operator.6252Instead of taking an index and extracting the corresponding character,6253it takes a character and finds the index where that character6254appears. If the character is not found, the function returns {\tt6255-1}.62566257This is the first example we have seen of a {\tt return} statement6258inside a loop. If {\tt word[index] == letter}, the function breaks6259out of the loop and returns immediately.62606261If the character doesn't appear in the string, the program6262exits the loop normally and returns {\tt -1}.62636264This pattern of computation---traversing a sequence and returning6265when we find what we are looking for---is called a {\bf search}.6266\index{traversal}6267\index{search pattern}6268\index{pattern!search}62696270As an exercise, modify {\tt find} so that it has a6271third parameter, the index in {\tt word} where it should start6272looking.627362746275\section{Looping and counting}6276\label{counter}6277\index{counter}6278\index{counting and looping}6279\index{looping and counting}6280\index{looping!with strings}62816282The following program counts the number of times the letter {\tt a}6283appears in a string:62846285\begin{verbatim}6286word = 'banana'6287count = 06288for letter in word:6289if letter == 'a':6290count = count + 16291print(count)6292\end{verbatim}6293%6294This program demonstrates another pattern of computation called a {\bf6295counter}. The variable {\tt count} is initialized to 0 and then6296incremented each time an {\tt a} is found.6297When the loop exits, {\tt count}6298contains the result---the total number of {\tt a}'s.62996300\index{encapsulation}6301As an exercise, encapsulate this code in a function named {\tt6302count}, and generalize it so that it accepts the string and the6303letter as arguments.63046305Then rewrite the function so that instead of6306traversing the string, it uses the three-parameter version of {\tt6307find} from the previous section.630863096310\section{String methods}6311\label{optional}63126313Strings provide methods that perform a variety of useful operations.6314A method is similar to a function---it takes arguments and6315returns a value---but the syntax is different. For example, the6316method {\tt upper} takes a string and returns a new string with6317all uppercase letters.6318\index{method}6319\index{string!method}63206321Instead of the function syntax {\tt upper(word)}, it uses6322the method syntax {\tt word.upper()}.63236324\begin{verbatim}6325>>> word = 'banana'6326>>> new_word = word.upper()6327>>> new_word6328'BANANA'6329\end{verbatim}6330%6331This form of dot notation specifies the name of the method, {\tt6332upper}, and the name of the string to apply the method to, {\tt6333word}. The empty parentheses indicate that this method takes no6334arguments.6335\index{parentheses!empty}6336\index{dot notation}63376338A method call is called an {\bf invocation}; in this case, we would6339say that we are invoking {\tt upper} on {\tt word}.6340\index{invocation}63416342As it turns out, there is a string method named {\tt find} that6343is remarkably similar to the function we wrote:63446345\begin{verbatim}6346>>> word = 'banana'6347>>> index = word.find('a')6348>>> index634916350\end{verbatim}6351%6352In this example, we invoke {\tt find} on {\tt word} and pass6353the letter we are looking for as a parameter.63546355Actually, the {\tt find} method is more general than our function;6356it can find substrings, not just characters:63576358\begin{verbatim}6359>>> word.find('na')636026361\end{verbatim}6362%6363By default, {\tt find} starts at the beginning of the string, but6364it can take a second argument, the index where it should start:6365\index{optional argument}6366\index{argument!optional}63676368\begin{verbatim}6369>>> word.find('na', 3)637046371\end{verbatim}6372%6373This is an example of an {\bf optional argument};6374{\tt find} can6375also take a third argument, the index where it should stop:63766377\begin{verbatim}6378>>> name = 'bob'6379>>> name.find('b', 1, 2)6380-16381\end{verbatim}6382%6383This search fails because {\tt b} does not6384appear in the index range from {\tt 1} to {\tt 2}, not including {\tt63852}. Searching up to, but not including, the second index makes6386{\tt find} consistent with the slice operator.6387638863896390\section{The {\tt in} operator}6391\label{inboth}6392\index{in operator}6393\index{operator!in}6394\index{boolean operator}6395\index{operator!boolean}63966397The word {\tt in} is a boolean operator that takes two strings and6398returns {\tt True} if the first appears as a substring in the second:63996400\begin{verbatim}6401>>> 'a' in 'banana'6402True6403>>> 'seed' in 'banana'6404False6405\end{verbatim}6406%6407For example, the following function prints all the6408letters from {\tt word1} that also appear in {\tt word2}:64096410\begin{verbatim}6411def in_both(word1, word2):6412for letter in word1:6413if letter in word2:6414print(letter)6415\end{verbatim}6416%6417With well-chosen variable names,6418Python sometimes reads like English. You could read6419this loop, ``for (each) letter in (the first) word, if (the) letter6420(appears) in (the second) word, print (the) letter.''64216422Here's what you get if you compare apples and oranges:64236424\begin{verbatim}6425>>> in_both('apples', 'oranges')6426a6427e6428s6429\end{verbatim}6430%64316432\section{String comparison}6433\index{string!comparison}6434\index{comparison!string}64356436The relational operators work on strings. To see if two strings are equal:64376438\begin{verbatim}6439if word == 'banana':6440print('All right, bananas.')6441\end{verbatim}6442%6443Other relational operations are useful for putting words in alphabetical6444order:64456446\begin{verbatim}6447if word < 'banana':6448print('Your word, ' + word + ', comes before banana.')6449elif word > 'banana':6450print('Your word, ' + word + ', comes after banana.')6451else:6452print('All right, bananas.')6453\end{verbatim}6454%6455Python does not handle uppercase and lowercase letters the same way6456people do. All the uppercase letters come before all the6457lowercase letters, so:64586459\begin{verbatim}6460Your word, Pineapple, comes before banana.6461\end{verbatim}6462%6463A common way to address this problem is to convert strings to a6464standard format, such as all lowercase, before performing the6465comparison. Keep that in mind in case you have to defend yourself6466against a man armed with a Pineapple.646764686469\section{Debugging}6470\index{debugging}6471\index{traversal}64726473When you use indices to traverse the values in a sequence,6474it is tricky to get the beginning and end of the traversal6475right. Here is a function that is supposed to compare two6476words and return {\tt True} if one of the words is the reverse6477of the other, but it contains two errors:64786479\begin{verbatim}6480def is_reverse(word1, word2):6481if len(word1) != len(word2):6482return False64836484i = 06485j = len(word2)64866487while j > 0:6488if word1[i] != word2[j]:6489return False6490i = i+16491j = j-164926493return True6494\end{verbatim}6495%6496The first {\tt if} statement checks whether the words are the6497same length. If not, we can return {\tt False} immediately.6498Otherwise, for the rest of the function, we can assume that the words6499are the same length. This is an example of the guardian pattern6500in Section~\ref{guardian}.6501\index{guardian pattern}6502\index{pattern!guardian}6503\index{index}65046505{\tt i} and {\tt j} are indices: {\tt i} traverses {\tt word1}6506forward while {\tt j} traverses {\tt word2} backward. If we find6507two letters that don't match, we can return {\tt False} immediately.6508If we get through the whole loop and all the letters match, we6509return {\tt True}.65106511If we test this function with the words ``pots'' and ``stop'', we6512expect the return value {\tt True}, but we get an IndexError:6513\index{IndexError}6514\index{exception!IndexError}65156516\begin{verbatim}6517>>> is_reverse('pots', 'stop')6518...6519File "reverse.py", line 15, in is_reverse6520if word1[i] != word2[j]:6521IndexError: string index out of range6522\end{verbatim}6523%6524For debugging this kind of error, my first move is to6525print the values of the indices immediately before the line6526where the error appears.65276528\begin{verbatim}6529while j > 0:6530print(i, j) # print here65316532if word1[i] != word2[j]:6533return False6534i = i+16535j = j-16536\end{verbatim}6537%6538Now when I run the program again, I get more information:65396540\begin{verbatim}6541>>> is_reverse('pots', 'stop')65420 46543...6544IndexError: string index out of range6545\end{verbatim}6546%6547The first time through the loop, the value of {\tt j} is 4,6548which is out of range for the string \verb"'pots'".6549The index of the last character is 3, so the6550initial value for {\tt j} should be {\tt len(word2)-1}.65516552If I fix that error and run the program again, I get:65536554\begin{verbatim}6555>>> is_reverse('pots', 'stop')65560 365571 265582 16559True6560\end{verbatim}6561%6562This time we get the right answer, but it looks like the loop only ran6563three times, which is suspicious. To get a better idea of what is6564happening, it is useful to draw a state diagram. During the first6565iteration, the frame for \verb"is_reverse" is shown in6566Figure~\ref{fig.state4}. \index{state diagram} \index{diagram!state}65676568\begin{figure}6569\centerline6570{\includegraphics[scale=0.8]{figs/state4.pdf}}6571\caption{State diagram.}6572\label{fig.state4}6573\end{figure}65746575I took some license by arranging the variables in the frame6576and adding dotted lines to show that the values of {\tt i} and6577{\tt j} indicate characters in {\tt word1} and {\tt word2}.65786579Starting with this diagram, run the program on paper, changing the6580values of {\tt i} and {\tt j} during each iteration. Find and fix the6581second error in this function.6582\label{isreverse}658365846585\section{Glossary}65866587\begin{description}65886589\item[object:] Something a variable can refer to. For now,6590you can use ``object'' and ``value'' interchangeably.6591\index{object}65926593\item[sequence:] An ordered collection of6594values where each value is identified by an integer index.6595\index{sequence}65966597\item[item:] One of the values in a sequence.6598\index{item}65996600\item[index:] An integer value used to select an item in6601a sequence, such as a character in a string. In Python6602indices start from 0.6603\index{index}66046605\item[slice:] A part of a string specified by a range of indices.6606\index{slice}66076608\item[empty string:] A string with no characters and length 0, represented6609by two quotation marks.6610\index{empty string}66116612\item[immutable:] The property of a sequence whose items cannot6613be changed.6614\index{immutability}66156616\item[traverse:] To iterate through the items in a sequence,6617performing a similar operation on each.6618\index{traversal}66196620\item[search:] A pattern of traversal that stops6621when it finds what it is looking for.6622\index{search pattern}6623\index{pattern!search}66246625\item[counter:] A variable used to count something, usually initialized6626to zero and then incremented.6627\index{counter}66286629\item[invocation:] A statement that calls a method.6630\index{invocation}66316632\item[optional argument:] A function or method argument that is not6633required.6634\index{optional argument}6635\index{argument!optional}66366637\end{description}663866396640\section{Exercises}66416642\begin{exercise}6643\index{string method}6644\index{method!string}66456646Read the documentation of the string methods at6647\url{http://docs.python.org/3/library/stdtypes.html#string-methods}.6648You might want to experiment with some of them to make sure you6649understand how they work. {\tt strip} and {\tt replace} are6650particularly useful.66516652The documentation uses a syntax that might be confusing.6653For example, in \verb"find(sub[, start[, end]])", the brackets6654indicate optional arguments. So {\tt sub} is required, but6655{\tt start} is optional, and if you include {\tt start},6656then {\tt end} is optional.6657\index{optional argument}6658\index{argument!optional}66596660\end{exercise}666166626663\begin{exercise}6664\index{count method}6665\index{method!count}66666667There is a string method called {\tt count} that is similar6668to the function in Section~\ref{counter}. Read the documentation6669of this method6670and write an invocation that counts the number of {\tt a}'s6671in \verb"'banana'".6672\end{exercise}667366746675\begin{exercise}6676\index{step size}6677\index{slice operator}6678\index{operator!slice}66796680A string slice can take a third index that specifies the ``step6681size''; that is, the number of spaces between successive characters.6682A step size of 2 means every other character; 3 means every third,6683etc.66846685\begin{verbatim}6686>>> fruit = 'banana'6687>>> fruit[0:5:2]6688'bnn'6689\end{verbatim}66906691A step size of -1 goes through the word backwards, so6692the slice \verb"[::-1]" generates a reversed string.6693\index{palindrome}66946695Use this idiom to write a one-line version of \verb"is_palindrome"6696from Exercise~\ref{palindrome}.6697\end{exercise}669866996700\begin{exercise}67016702The following functions are all {\em intended} to check whether a6703string contains any lowercase letters, but at least some of them are6704wrong. For each function, describe what the function actually does6705(assuming that the parameter is a string).67066707\begin{verbatim}6708def any_lowercase1(s):6709for c in s:6710if c.islower():6711return True6712else:6713return False67146715def any_lowercase2(s):6716for c in s:6717if 'c'.islower():6718return 'True'6719else:6720return 'False'67216722def any_lowercase3(s):6723for c in s:6724flag = c.islower()6725return flag67266727def any_lowercase4(s):6728flag = False6729for c in s:6730flag = flag or c.islower()6731return flag67326733def any_lowercase5(s):6734for c in s:6735if not c.islower():6736return False6737return True6738\end{verbatim}67396740\end{exercise}674167426743\begin{exercise}6744\index{letter rotation}6745\index{rotation, letter}67466747\label{exrotate}6748A Caesar cypher is a weak form of encryption that involves ``rotating'' each6749letter by a fixed number of places. To rotate a letter means6750to shift it through the alphabet, wrapping around to the beginning if6751necessary, so 'A' rotated by 3 is 'D' and 'Z' rotated by 1 is 'A'.67526753To rotate a word, rotate each letter by the same amount.6754For example, ``cheer'' rotated by 7 is ``jolly'' and ``melon'' rotated6755by -10 is ``cubed''. In the movie {\em 2001: A Space Odyssey}, the6756ship computer is called HAL, which is IBM rotated by -1.67576758%For example ``sleep''6759%rotated by 9 is ``bunny'' and ``latex'' rotated by 7 is ``shale''.67606761Write a function called \verb"rotate_word"6762that takes a string and an integer as parameters, and returns6763a new string that contains the letters from the original string6764rotated by the given amount.67656766You might want to use the built-in function {\tt ord}, which converts6767a character to a numeric code, and {\tt chr}, which converts numeric6768codes to characters. Letters of the alphabet are encoded in alphabetical6769order, so for example:67706771\begin{verbatim}6772>>> ord('c') - ord('a')677326774\end{verbatim}67756776Because \verb"'c'" is the two-eth letter of the alphabet. But6777beware: the numeric codes for upper case letters are different.67786779Potentially offensive jokes on the Internet are sometimes encoded in6780ROT13, which is a Caesar cypher with rotation 13. If you are not6781easily offended, find and decode some of them. Solution:6782\url{http://thinkpython2.com/code/rotate.py}.67836784\end{exercise}678567866787\chapter{Case study: word play}6788\label{wordplay}67896790This chapter presents the second case study, which involves6791solving word puzzles by searching for words that have certain6792properties. For example, we'll find the longest palindromes6793in English and search for words whose letters appear in6794alphabetical order. And I will present another program development6795plan: reduction to a previously solved problem.679667976798\section{Reading word lists}6799\label{wordlist}68006801For the exercises in this chapter we need a list of English words.6802There are lots of word lists available on the Web, but the one most6803suitable for our purpose is one of the word lists collected and6804contributed to the public domain by Grady Ward as part of the Moby6805lexicon project (see \url{http://wikipedia.org/wiki/Moby_Project}). It6806is a list of 113,809 official crosswords; that is, words that are6807considered valid in crossword puzzles and other word games. In the6808Moby collection, the filename is {\tt 113809of.fic}; you can download6809a copy, with the simpler name {\tt words.txt}, from6810\url{http://thinkpython2.com/code/words.txt}.6811\index{Moby Project}6812\index{crosswords}68136814This file is in plain text, so you can open it with a text6815editor, but you can also read it from Python. The built-in6816function {\tt open} takes the name of the file as a parameter6817and returns a {\bf file object} you can use to read the file.6818\index{open function}6819\index{function!open}6820\index{plain text}6821\index{text!plain}6822\index{object!file}6823\index{file object}68246825\begin{verbatim}6826>>> fin = open('words.txt')6827\end{verbatim}6828%6829{\tt fin} is a common name for a file object used for input. The file6830object provides several methods for reading, including {\tt readline},6831which reads characters from the file until it gets to a newline and6832returns the result as a string: \index{readline method}6833\index{method!readline}68346835\begin{verbatim}6836>>> fin.readline()6837'aa\n'6838\end{verbatim}6839%6840The first word in this particular list is ``aa'', which is a kind of6841lava. The sequence \verb"\n" represents the newline character that6842separates this word from the next.68436844The file object keeps track of where it is in the file, so6845if you call {\tt readline} again, you get the next word:68466847\begin{verbatim}6848>>> fin.readline()6849'aah\n'6850\end{verbatim}6851%6852The next word is ``aah'', which is a perfectly legitimate6853word, so stop looking at me like that.6854Or, if it's the newline character that's bothering you,6855we can get rid of it with the string method {\tt strip}:6856\index{strip method}6857\index{method!strip}68586859\begin{verbatim}6860>>> line = fin.readline()6861>>> word = line.strip()6862>>> word6863'aahed'6864\end{verbatim}6865%6866You can also use a file object as part of a {\tt for} loop.6867This program reads {\tt words.txt} and prints each word, one6868per line:6869\index{open function}6870\index{function!open}68716872\begin{verbatim}6873fin = open('words.txt')6874for line in fin:6875word = line.strip()6876print(word)6877\end{verbatim}6878%68796880\section{Exercises}68816882There are solutions to these exercises in the next section.6883You should at least attempt each one before you read the solutions.68846885\begin{exercise}6886Write a program that reads {\tt words.txt} and prints only the6887words with more than 20 characters (not counting whitespace).6888\index{whitespace}68896890\end{exercise}68916892\begin{exercise}68936894In 1939 Ernest Vincent Wright published a 50,000 word novel called6895{\em Gadsby} that does not contain the letter ``e''. Since ``e'' is6896the most common letter in English, that's not easy to do.68976898In fact, it is difficult to construct a solitary thought without using6899that most common symbol. It is slow going at first, but with caution6900and hours of training you can gradually gain facility.69016902All right, I'll stop now.69036904Write a function called \verb"has_no_e" that returns {\tt True} if6905the given word doesn't have the letter ``e'' in it.69066907Write a program that reads {\tt words.txt} and prints only the words6908that have no ``e''. Compute the percentage of words in the list6909that have no ``e''.6910\index{lipogram}69116912\end{exercise}691369146915\begin{exercise}69166917Write a function named {\tt avoids}6918that takes a word and a string of forbidden letters, and6919that returns {\tt True} if the word doesn't use any of the forbidden6920letters.69216922Write a program that prompts the user to enter a string6923of forbidden letters and then prints the number of words that6924don't contain any of them.6925Can you find a combination of 5 forbidden letters that6926excludes the smallest number of words?69276928\end{exercise}6929693069316932\begin{exercise}69336934Write a function named \verb"uses_only" that takes a word and a6935string of letters, and that returns {\tt True} if the word contains6936only letters in the list. Can you make a sentence using only the6937letters {\tt acefhlo}? Other than ``Hoe alfalfa''?69386939\end{exercise}694069416942\begin{exercise}69436944Write a function named \verb"uses_all" that takes a word and a6945string of required letters, and that returns {\tt True} if the word6946uses all the required letters at least once. How many words are there6947that use all the vowels {\tt aeiou}? How about {\tt aeiouy}?69486949\end{exercise}695069516952\begin{exercise}69536954Write a function called \verb"is_abecedarian" that returns6955{\tt True} if the letters in a word appear in alphabetical order6956(double letters are ok).6957How many abecedarian words are there?69586959\index{abecedarian}69606961\end{exercise}6962696369646965\section{Search}6966\label{search}6967\index{search pattern}6968\index{pattern!search}69696970All of the exercises in the previous section have something6971in common; they can be solved with the search pattern we saw6972in Section~\ref{find}. The simplest example is:69736974\begin{verbatim}6975def has_no_e(word):6976for letter in word:6977if letter == 'e':6978return False6979return True6980\end{verbatim}6981%6982The {\tt for} loop traverses the characters in {\tt word}. If we find6983the letter ``e'', we can immediately return {\tt False}; otherwise we6984have to go to the next letter. If we exit the loop normally, that6985means we didn't find an ``e'', so we return {\tt True}.6986\index{traversal}69876988\index{in operator}6989\index{operator!in}6990You could write this function more concisely using the {\tt in}6991operator, but I started with this version because it6992demonstrates the logic of the search pattern.69936994\index{generalization}6995{\tt avoids} is a more general version of \verb"has_no_e" but it6996has the same structure:69976998\begin{verbatim}6999def avoids(word, forbidden):7000for letter in word:7001if letter in forbidden:7002return False7003return True7004\end{verbatim}7005%7006We can return {\tt False} as soon as we find a forbidden letter;7007if we get to the end of the loop, we return {\tt True}.70087009\verb"uses_only" is similar except that the sense of the condition7010is reversed:70117012\begin{verbatim}7013def uses_only(word, available):7014for letter in word:7015if letter not in available:7016return False7017return True7018\end{verbatim}7019%7020Instead of a list of forbidden letters, we have a list of available7021letters. If we find a letter in {\tt word} that is not in7022{\tt available}, we can return {\tt False}.70237024\verb"uses_all" is similar except that we reverse the role7025of the word and the string of letters:70267027\begin{verbatim}7028def uses_all(word, required):7029for letter in required:7030if letter not in word:7031return False7032return True7033\end{verbatim}7034%7035Instead of traversing the letters in {\tt word}, the loop7036traverses the required letters. If any of the required letters7037do not appear in the word, we can return {\tt False}.7038\index{traversal}70397040If you were really thinking like a computer scientist, you would7041have recognized that \verb"uses_all" was an instance of a7042previously solved problem, and you would have written:70437044\begin{verbatim}7045def uses_all(word, required):7046return uses_only(required, word)7047\end{verbatim}7048%7049This is an example of a program development plan called {\bf7050reduction to a previously solved problem}, which means that you7051recognize the problem you are working on as an instance of a solved7052problem and apply an existing solution. \index{reduction to a7053previously solved problem} \index{development plan!reduction}705470557056\section{Looping with indices}7057\index{looping!with indices}7058\index{index!looping with}70597060I wrote the functions in the previous section with {\tt for}7061loops because I only needed the characters in the strings; I didn't7062have to do anything with the indices.70637064For \verb"is_abecedarian" we have to compare adjacent letters,7065which is a little tricky with a {\tt for} loop:70667067\begin{verbatim}7068def is_abecedarian(word):7069previous = word[0]7070for c in word:7071if c < previous:7072return False7073previous = c7074return True7075\end{verbatim}70767077An alternative is to use recursion:70787079\begin{verbatim}7080def is_abecedarian(word):7081if len(word) <= 1:7082return True7083if word[0] > word[1]:7084return False7085return is_abecedarian(word[1:])7086\end{verbatim}70877088Another option is to use a {\tt while} loop:70897090\begin{verbatim}7091def is_abecedarian(word):7092i = 07093while i < len(word)-1:7094if word[i+1] < word[i]:7095return False7096i = i+17097return True7098\end{verbatim}7099%7100The loop starts at {\tt i=0} and ends when {\tt i=len(word)-1}. Each7101time through the loop, it compares the $i$th character (which you can7102think of as the current character) to the $i+1$th character (which you7103can think of as the next).71047105If the next character is less than (alphabetically before) the current7106one, then we have discovered a break in the abecedarian trend, and7107we return {\tt False}.71087109If we get to the end of the loop without finding a fault, then the7110word passes the test. To convince yourself that the loop ends7111correctly, consider an example like \verb"'flossy'". The7112length of the word is 6, so7113the last time the loop runs is when {\tt i} is 4, which is the7114index of the second-to-last character. On the last iteration,7115it compares the second-to-last character to the last, which is7116what we want.7117\index{palindrome}71187119Here is a version of \verb"is_palindrome" (see7120Exercise~\ref{palindrome}) that uses two indices; one starts at the7121beginning and goes up; the other starts at the end and goes down.71227123\begin{verbatim}7124def is_palindrome(word):7125i = 07126j = len(word)-171277128while i<j:7129if word[i] != word[j]:7130return False7131i = i+17132j = j-171337134return True7135\end{verbatim}71367137Or we could reduce to a previously solved7138problem and write:7139\index{reduction to a previously solved problem}7140\index{development plan!reduction}71417142\begin{verbatim}7143def is_palindrome(word):7144return is_reverse(word, word)7145\end{verbatim}7146%7147Using \verb"is_reverse" from Section~\ref{isreverse}.714871497150\section{Debugging}7151\index{debugging}7152\index{testing!is hard}7153\index{program testing}71547155Testing programs is hard. The functions in this chapter are7156relatively easy to test because you can check the results by hand.7157Even so, it is somewhere between difficult and impossible to choose a7158set of words that test for all possible errors.71597160Taking \verb"has_no_e" as an example, there are two obvious7161cases to check: words that have an `e' should return {\tt False}, and7162words that don't should return {\tt True}. You should have no7163trouble coming up with one of each.71647165Within each case, there are some less obvious subcases. Among the7166words that have an ``e'', you should test words with an ``e'' at the7167beginning, the end, and somewhere in the middle. You should test long7168words, short words, and very short words, like the empty string. The7169empty string is an example of a {\bf special case}, which is one of7170the non-obvious cases where errors often lurk.7171\index{special case}71727173In addition to the test cases you generate, you can also test7174your program with a word list like {\tt words.txt}. By scanning7175the output, you might be able to catch errors, but be careful:7176you might catch one kind of error (words that should not be7177included, but are) and not another (words that should be included,7178but aren't).71797180In general, testing can help you find bugs, but it is not easy to7181generate a good set of test cases, and even if you do, you can't7182be sure your program is correct.7183According to a legendary computer scientist:7184\index{testing!and absence of bugs}71857186\begin{quote}7187Program testing can be used to show the presence of bugs, but never to7188show their absence!71897190--- Edsger W. Dijkstra7191\end{quote}7192\index{Dijkstra, Edsger}719371947195\section{Glossary}71967197\begin{description}71987199\item[file object:] A value that represents an open file.7200\index{file object}7201\index{object!file}72027203\item[reduction to a previously solved problem:] A way of solving a7204problem by expressing it as an instance of a previously solved7205problem. \index{reduction to a previously solved problem}7206\index{development plan!reduction}72077208\item[special case:] A test case that is atypical or non-obvious7209(and less likely to be handled correctly).7210\index{special case}72117212\end{description}721372147215\section{Exercises}72167217\begin{exercise}7218\index{Car Talk}7219\index{Puzzler}7220\index{double letters}72217222This question is based on a Puzzler that was broadcast on the radio7223program {\em Car Talk}7224(\url{http://www.cartalk.com/content/puzzlers}):72257226\begin{quote}7227Give me a word with three consecutive double letters. I'll give you a7228couple of words that almost qualify, but don't. For example, the word7229committee, c-o-m-m-i-t-t-e-e. It would be great except for the `i' that7230sneaks in there. Or Mississippi: M-i-s-s-i-s-s-i-p-p-i. If you could7231take out those i's it would work. But there is a word that has three7232consecutive pairs of letters and to the best of my knowledge this may7233be the only word. Of course there are probably 500 more but I can only7234think of one. What is the word?7235\end{quote}72367237Write a program to find it.7238Solution: \url{http://thinkpython2.com/code/cartalk1.py}.72397240\end{exercise}724172427243\begin{exercise}7244Here's another {\em Car Talk}7245Puzzler (\url{http://www.cartalk.com/content/puzzlers}):7246\index{Car Talk}7247\index{Puzzler}7248\index{odometer}7249\index{palindrome}72507251\begin{quote}7252``I was driving on the highway the other day and I happened to7253notice my odometer. Like most odometers, it shows six digits,7254in whole miles only. So, if my car had 300,0007255miles, for example, I'd see 3-0-0-0-0-0.72567257``Now, what I saw that day was very interesting. I noticed that the7258last 4 digits were palindromic; that is, they read the same forward as7259backward. For example, 5-4-4-5 is a palindrome, so my odometer7260could have read 3-1-5-4-4-5.72617262``One mile later, the last 5 numbers were palindromic. For example, it7263could have read 3-6-5-4-5-6. One mile after that, the middle 4 out of72646 numbers were palindromic. And you ready for this? One mile later,7265all 6 were palindromic!72667267``The question is, what was on the odometer when I first looked?''7268\end{quote}72697270Write a Python program that tests all the six-digit numbers and prints7271any numbers that satisfy these requirements.7272Solution: \url{http://thinkpython2.com/code/cartalk2.py}.72737274\end{exercise}727572767277\begin{exercise}7278Here's another {\em Car Talk} Puzzler you can solve with a7279search (\url{http://www.cartalk.com/content/puzzlers}):7280\index{Car Talk}7281\index{Puzzler}7282\index{palindrome}72837284\begin{quote}7285``Recently I had a visit with my mom and we realized that7286the two digits that make up my age when reversed resulted in her7287age. For example, if she's 73, I'm 37. We wondered how often this has7288happened over the years but we got sidetracked with other topics and7289we never came up with an answer.72907291``When I got home I figured out that the digits of our ages have been7292reversible six times so far. I also figured out that if we're lucky it7293would happen again in a few years, and if we're really lucky it would7294happen one more time after that. In other words, it would have7295happened 8 times over all. So the question is, how old am I now?''72967297\end{quote}72987299Write a Python program that searches for solutions to this Puzzler.7300Hint: you might find the string method {\tt zfill} useful.73017302Solution: \url{http://thinkpython2.com/code/cartalk3.py}.73037304\end{exercise}7305730673077308\chapter{Lists}73097310This chapter presents one of Python's most useful built-in types, lists.7311You will also learn more about objects and what can happen when you have7312more than one name for the same object.731373147315\section{A list is a sequence}7316\label{sequence}73177318Like a string, a {\bf list} is a sequence of values. In a string, the7319values are characters; in a list, they can be any type. The values in7320a list are called {\bf elements} or sometimes {\bf items}.7321\index{list}7322\index{type!list}7323\index{element}7324\index{sequence}7325\index{item}73267327There are several ways to create a new list; the simplest is to7328enclose the elements in square brackets (\verb"[" and \verb"]"):73297330\begin{verbatim}7331[10, 20, 30, 40]7332['crunchy frog', 'ram bladder', 'lark vomit']7333\end{verbatim}7334%7335The first example is a list of four integers. The second is a list of7336three strings. The elements of a list don't have to be the same type.7337The following list contains a string, a float, an integer, and7338(lo!) another list:73397340\begin{verbatim}7341['spam', 2.0, 5, [10, 20]]7342\end{verbatim}7343%7344A list within another list is {\bf nested}.7345\index{nested list}7346\index{list!nested}73477348A list that contains no elements is7349called an empty list; you can create one with empty7350brackets, \verb"[]".7351\index{empty list}7352\index{list!empty}73537354As you might expect, you can assign list values to variables:73557356\begin{verbatim}7357>>> cheeses = ['Cheddar', 'Edam', 'Gouda']7358>>> numbers = [42, 123]7359>>> empty = []7360>>> print(cheeses, numbers, empty)7361['Cheddar', 'Edam', 'Gouda'] [42, 123] []7362\end{verbatim}7363%7364\index{assignment}736573667367\section{Lists are mutable}7368\label{mutable}7369\index{list!element}7370\index{access}7371\index{index}7372\index{bracket operator}7373\index{operator!bracket}73747375The syntax for accessing the elements of a list is the same as for7376accessing the characters of a string---the bracket operator. The7377expression inside the brackets specifies the index. Remember that the7378indices start at 0:73797380\begin{verbatim}7381>>> cheeses[0]7382'Cheddar'7383\end{verbatim}7384%7385Unlike strings, lists are mutable. When the bracket operator appears7386on the left side of an assignment, it identifies the element of the7387list that will be assigned.7388\index{mutability}73897390\begin{verbatim}7391>>> numbers = [42, 123]7392>>> numbers[1] = 57393>>> numbers7394[42, 5]7395\end{verbatim}7396%7397The one-eth element of {\tt numbers}, which7398used to be 123, is now 5.7399\index{index!starting at zero}7400\index{zero, index starting at}74017402Figure~\ref{fig.liststate} shows7403the state diagram for {\tt7404cheeses}, {\tt numbers} and {\tt empty}:7405\index{state diagram}7406\index{diagram!state}74077408\begin{figure}7409\centerline7410{\includegraphics[scale=0.8]{figs/liststate.pdf}}7411\caption{State diagram.}7412\label{fig.liststate}7413\end{figure}74147415Lists are represented by boxes with the word ``list'' outside7416and the elements of the list inside. {\tt cheeses} refers to7417a list with three elements indexed 0, 1 and 2.7418{\tt numbers} contains two elements; the diagram shows that the7419value of the second element has been reassigned from 123 to 5.7420{\tt empty} refers to a list with no elements.7421\index{item assignment}7422\index{assignment!item}7423\index{reassignment}74247425List indices work the same way as string indices:74267427\begin{itemize}74287429\item Any integer expression can be used as an index.74307431\item If you try to read or write an element that does not exist, you7432get an {\tt IndexError}.7433\index{exception!IndexError}7434\index{IndexError}74357436\item If an index has a negative value, it counts backward from the7437end of the list.74387439\end{itemize}7440\index{list!index}74417442\index{list!membership}7443\index{membership!list}7444\index{in operator}7445\index{operator!in}74467447The {\tt in} operator also works on lists.74487449\begin{verbatim}7450>>> cheeses = ['Cheddar', 'Edam', 'Gouda']7451>>> 'Edam' in cheeses7452True7453>>> 'Brie' in cheeses7454False7455\end{verbatim}745674577458\section{Traversing a list}7459\index{list!traversal}7460\index{traversal!list}7461\index{for loop}7462\index{loop!for}7463\index{statement!for}74647465The most common way to traverse the elements of a list is7466with a {\tt for} loop. The syntax is the same as for strings:74677468\begin{verbatim}7469for cheese in cheeses:7470print(cheese)7471\end{verbatim}7472%7473This works well if you only need to read the elements of the7474list. But if you want to write or update the elements, you7475need the indices. A common way to do that is to combine7476the built-in functions {\tt range} and {\tt len}:7477\index{looping!with indices}7478\index{index!looping with}74797480\begin{verbatim}7481for i in range(len(numbers)):7482numbers[i] = numbers[i] * 27483\end{verbatim}7484%7485This loop traverses the list and updates each element. {\tt len}7486returns the number of elements in the list. {\tt range} returns7487a list of indices from 0 to $n-1$, where $n$ is the length of7488the list. Each time through the loop {\tt i} gets the index7489of the next element. The assignment statement in the body uses7490{\tt i} to read the old value of the element and to assign the7491new value.7492\index{item update}7493\index{update!item}74947495A {\tt for} loop over an empty list never runs the body:74967497\begin{verbatim}7498for x in []:7499print('This never happens.')7500\end{verbatim}7501%7502Although a list can contain another list, the nested7503list still counts as a single element. The length of this list is7504four:7505\index{nested list}7506\index{list!nested}75077508\begin{verbatim}7509['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]7510\end{verbatim}7511751275137514\section{List operations}7515\index{list!operation}75167517The {\tt +} operator concatenates lists:7518\index{concatenation!list}7519\index{list!concatenation}75207521\begin{verbatim}7522>>> a = [1, 2, 3]7523>>> b = [4, 5, 6]7524>>> c = a + b7525>>> c7526[1, 2, 3, 4, 5, 6]7527\end{verbatim}7528%7529The {\tt *} operator repeats a list a given number of times:7530\index{repetition!list}7531\index{list!repetition}75327533\begin{verbatim}7534>>> [0] * 47535[0, 0, 0, 0]7536>>> [1, 2, 3] * 37537[1, 2, 3, 1, 2, 3, 1, 2, 3]7538\end{verbatim}7539%7540The first example repeats {\tt [0]} four times. The second example7541repeats the list {\tt [1, 2, 3]} three times.754275437544\section{List slices}7545\index{slice operator}7546\index{operator!slice}7547\index{index!slice}7548\index{list!slice}7549\index{slice!list}75507551The slice operator also works on lists:75527553\begin{verbatim}7554>>> t = ['a', 'b', 'c', 'd', 'e', 'f']7555>>> t[1:3]7556['b', 'c']7557>>> t[:4]7558['a', 'b', 'c', 'd']7559>>> t[3:]7560['d', 'e', 'f']7561\end{verbatim}7562%7563If you omit the first index, the slice starts at the beginning.7564If you omit the second, the slice goes to the end. So if you7565omit both, the slice is a copy of the whole list.7566\index{list!copy}7567\index{slice!copy}7568\index{copy!slice}75697570\begin{verbatim}7571>>> t[:]7572['a', 'b', 'c', 'd', 'e', 'f']7573\end{verbatim}7574%7575Since lists are mutable, it is often useful to make a copy7576before performing operations that modify lists.7577\index{mutability}75787579A slice operator on the left side of an assignment7580can update multiple elements:7581\index{slice!update}7582\index{update!slice}75837584\begin{verbatim}7585>>> t = ['a', 'b', 'c', 'd', 'e', 'f']7586>>> t[1:3] = ['x', 'y']7587>>> t7588['a', 'x', 'y', 'd', 'e', 'f']7589\end{verbatim}7590%75917592% You can add elements to a list by squeezing them into an empty7593% slice:75947595% % \begin{verbatim}7596% >>> t = ['a', 'd', 'e', 'f']7597% >>> t[1:1] = ['b', 'c']7598% >>> print t7599% ['a', 'b', 'c', 'd', 'e', 'f']7600% \end{verbatim}7601% \afterverb7602%7603% And you can remove elements from a list by assigning the empty list to7604% them:76057606% % \begin{verbatim}7607% >>> t = ['a', 'b', 'c', 'd', 'e', 'f']7608% >>> t[1:3] = []7609% >>> print t7610% ['a', 'd', 'e', 'f']7611% \end{verbatim}7612% \afterverb7613%7614% But both of those operations can be expressed more clearly7615% with list methods.761676177618\section{List methods}7619\index{list!method}7620\index{method, list}76217622Python provides methods that operate on lists. For example,7623{\tt append} adds a new element to the end of a list:7624\index{append method}7625\index{method!append}76267627\begin{verbatim}7628>>> t = ['a', 'b', 'c']7629>>> t.append('d')7630>>> t7631['a', 'b', 'c', 'd']7632\end{verbatim}7633%7634{\tt extend} takes a list as an argument and appends all of7635the elements:7636\index{extend method}7637\index{method!extend}76387639\begin{verbatim}7640>>> t1 = ['a', 'b', 'c']7641>>> t2 = ['d', 'e']7642>>> t1.extend(t2)7643>>> t17644['a', 'b', 'c', 'd', 'e']7645\end{verbatim}7646%7647This example leaves {\tt t2} unmodified.76487649{\tt sort} arranges the elements of the list from low to high:7650\index{sort method}7651\index{method!sort}76527653\begin{verbatim}7654>>> t = ['d', 'c', 'e', 'b', 'a']7655>>> t.sort()7656>>> t7657['a', 'b', 'c', 'd', 'e']7658\end{verbatim}7659%7660Most list methods are void; they modify the list and return {\tt None}.7661If you accidentally write {\tt t = t.sort()}, you will be disappointed7662with the result.7663\index{void method}7664\index{method!void}7665\index{None special value}7666\index{special value!None}766776687669\section{Map, filter and reduce}7670\label{filter}76717672To add up all the numbers in a list, you can use a loop like this:76737674% see add.py76757676\begin{verbatim}7677def add_all(t):7678total = 07679for x in t:7680total += x7681return total7682\end{verbatim}7683%7684{\tt total} is initialized to 0. Each time through the loop,7685{\tt x} gets one element from the list. The {\tt +=} operator7686provides a short way to update a variable. This7687{\bf augmented assignment statement},7688\index{update operator}7689\index{operator!update}7690\index{assignment!augmented}7691\index{augmented assignment}76927693\begin{verbatim}7694total += x7695\end{verbatim}7696%7697is equivalent to76987699\begin{verbatim}7700total = total + x7701\end{verbatim}7702%7703As the loop runs, {\tt total} accumulates the sum of the7704elements; a variable used this way is sometimes called an7705{\bf accumulator}.7706\index{accumulator!sum}77077708Adding up the elements of a list is such a common operation7709that Python provides it as a built-in function, {\tt sum}:77107711\begin{verbatim}7712>>> t = [1, 2, 3]7713>>> sum(t)771467715\end{verbatim}7716%7717An operation like this that combines a sequence of elements into7718a single value is sometimes called {\bf reduce}.7719\index{reduce pattern}7720\index{pattern!reduce}7721\index{traversal}77227723Sometimes you want to traverse one list while building7724another. For example, the following function takes a list of strings7725and returns a new list that contains capitalized strings:77267727\begin{verbatim}7728def capitalize_all(t):7729res = []7730for s in t:7731res.append(s.capitalize())7732return res7733\end{verbatim}7734%7735{\tt res} is initialized with an empty list; each time through7736the loop, we append the next element. So {\tt res} is another7737kind of accumulator.7738\index{accumulator!list}77397740An operation like \verb"capitalize_all" is sometimes called a {\bf7741map} because it ``maps'' a function (in this case the method {\tt7742capitalize}) onto each of the elements in a sequence.7743\index{map pattern}7744\index{pattern!map}7745\index{filter pattern}7746\index{pattern!filter}77477748Another common operation is to select some of the elements from7749a list and return a sublist. For example, the following7750function takes a list of strings and returns a list that contains7751only the uppercase strings:77527753\begin{verbatim}7754def only_upper(t):7755res = []7756for s in t:7757if s.isupper():7758res.append(s)7759return res7760\end{verbatim}7761%7762{\tt isupper} is a string method that returns {\tt True} if7763the string contains only upper case letters.77647765An operation like \verb"only_upper" is called a {\bf filter} because7766it selects some of the elements and filters out the others.77677768Most common list operations can be expressed as a combination7769of map, filter and reduce.777077717772\section{Deleting elements}7773\index{element deletion}7774\index{deletion, element of list}77757776There are several ways to delete elements from a list. If you7777know the index of the element you want, you can use7778{\tt pop}:7779\index{pop method}7780\index{method!pop}77817782\begin{verbatim}7783>>> t = ['a', 'b', 'c']7784>>> x = t.pop(1)7785>>> t7786['a', 'c']7787>>> x7788'b'7789\end{verbatim}7790%7791{\tt pop} modifies the list and returns the element that was removed.7792If you don't provide an index, it deletes and returns the7793last element.77947795If you don't need the removed value, you can use the {\tt del}7796operator:7797\index{del operator}7798\index{operator!del}77997800\begin{verbatim}7801>>> t = ['a', 'b', 'c']7802>>> del t[1]7803>>> t7804['a', 'c']7805\end{verbatim}7806%7807If you know the element you want to remove (but not the index), you7808can use {\tt remove}:7809\index{remove method}7810\index{method!remove}78117812\begin{verbatim}7813>>> t = ['a', 'b', 'c']7814>>> t.remove('b')7815>>> t7816['a', 'c']7817\end{verbatim}7818%7819The return value from {\tt remove} is {\tt None}.7820\index{None special value}7821\index{special value!None}78227823To remove more than one element, you can use {\tt del} with7824a slice index:78257826\begin{verbatim}7827>>> t = ['a', 'b', 'c', 'd', 'e', 'f']7828>>> del t[1:5]7829>>> t7830['a', 'f']7831\end{verbatim}7832%7833As usual, the slice selects all the elements up to but not7834including the second index.7835783678377838\section{Lists and strings}7839\index{list}7840\index{string}7841\index{sequence}78427843A string is a sequence of characters and a list is a sequence7844of values, but a list of characters is not the same as a7845string. To convert from a string to a list of characters,7846you can use {\tt list}:7847\index{list!function}7848\index{function!list}78497850\begin{verbatim}7851>>> s = 'spam'7852>>> t = list(s)7853>>> t7854['s', 'p', 'a', 'm']7855\end{verbatim}7856%7857Because {\tt list} is the name of a built-in function, you should7858avoid using it as a variable name. I also avoid {\tt l} because7859it looks too much like {\tt 1}. So that's why I use {\tt t}.78607861The {\tt list} function breaks a string into individual letters. If7862you want to break a string into words, you can use the {\tt split}7863method:7864\index{split method}7865\index{method!split}78667867\begin{verbatim}7868>>> s = 'pining for the fjords'7869>>> t = s.split()7870>>> t7871['pining', 'for', 'the', 'fjords']7872\end{verbatim}7873%7874An optional argument called a {\bf delimiter} specifies which7875characters to use as word boundaries.7876The following example7877uses a hyphen as a delimiter:7878\index{optional argument}7879\index{argument!optional}7880\index{delimiter}78817882\begin{verbatim}7883>>> s = 'spam-spam-spam'7884>>> delimiter = '-'7885>>> t = s.split(delimiter)7886>>> t7887['spam', 'spam', 'spam']7888\end{verbatim}7889%7890{\tt join} is the inverse of {\tt split}. It7891takes a list of strings and7892concatenates the elements. {\tt join} is a string method,7893so you have to invoke it on the delimiter and pass the7894list as a parameter:7895\index{join method}7896\index{method!join}7897\index{concatenation}78987899\begin{verbatim}7900>>> t = ['pining', 'for', 'the', 'fjords']7901>>> delimiter = ' '7902>>> s = delimiter.join(t)7903>>> s7904'pining for the fjords'7905\end{verbatim}7906%7907In this case the delimiter is a space character, so7908{\tt join} puts a space between words. To concatenate7909strings without spaces, you can use the empty string,7910\verb"''", as a delimiter.7911\index{empty string}7912\index{string!empty}791379147915\section{Objects and values}7916\label{equivalence}7917\index{object}7918\index{value}79197920If we run these assignment statements:79217922\begin{verbatim}7923a = 'banana'7924b = 'banana'7925\end{verbatim}7926%7927We know that {\tt a} and {\tt b} both refer to a7928string, but we don't7929know whether they refer to the {\em same} string.7930There are two possible states, shown in Figure~\ref{fig.list1}.7931\index{aliasing}79327933\begin{figure}7934\centerline7935{\includegraphics[scale=0.8]{figs/list1.pdf}}7936\caption{State diagram.}7937\label{fig.list1}7938\end{figure}79397940In one case, {\tt a} and {\tt b} refer to two different objects that7941have the same value. In the second case, they refer to the same7942object.7943\index{is operator}7944\index{operator!is}79457946To check whether two variables refer to the same object, you can7947use the {\tt is} operator.79487949\begin{verbatim}7950>>> a = 'banana'7951>>> b = 'banana'7952>>> a is b7953True7954\end{verbatim}7955%7956In this example, Python only created one string object, and both {\tt7957a} and {\tt b} refer to it. But when you create two lists, you get7958two objects:79597960\begin{verbatim}7961>>> a = [1, 2, 3]7962>>> b = [1, 2, 3]7963>>> a is b7964False7965\end{verbatim}7966%7967So the state diagram looks like Figure~\ref{fig.list2}.7968\index{state diagram}7969\index{diagram!state}79707971\begin{figure}7972\centerline7973{\includegraphics[scale=0.8]{figs/list2.pdf}}7974\caption{State diagram.}7975\label{fig.list2}7976\end{figure}79777978In this case we would say that the two lists are {\bf equivalent},7979because they have the same elements, but not {\bf identical}, because7980they are not the same object. If two objects are identical, they are7981also equivalent, but if they are equivalent, they are not necessarily7982identical.7983\index{equivalence}7984\index{identity}79857986Until now, we have been using ``object'' and ``value''7987interchangeably, but it is more precise to say that an object has a7988value. If you evaluate {\tt [1, 2, 3]}, you get a list7989object whose value is a sequence of integers. If another7990list has the same elements, we say it has the same value, but7991it is not the same object.7992\index{object}7993\index{value}799479957996\section{Aliasing}7997\index{aliasing}7998\index{reference!aliasing}79998000If {\tt a} refers to an object and you assign {\tt b = a},8001then both variables refer to the same object:80028003\begin{verbatim}8004>>> a = [1, 2, 3]8005>>> b = a8006>>> b is a8007True8008\end{verbatim}8009%8010The state diagram looks like Figure~\ref{fig.list3}.8011\index{state diagram}8012\index{diagram!state}80138014\begin{figure}8015\centerline8016{\includegraphics[scale=0.8]{figs/list3.pdf}}8017\caption{State diagram.}8018\label{fig.list3}8019\end{figure}80208021The association of a variable with an object is called a {\bf8022reference}. In this example, there are two references to the same8023object.8024\index{reference}80258026An object with more than one reference has more8027than one name, so we say that the object is {\bf aliased}.8028\index{mutability}80298030If the aliased object is mutable, changes made with one alias affect8031the other:80328033\begin{verbatim}8034>>> b[0] = 428035>>> a8036[42, 2, 3]8037\end{verbatim}8038%8039Although this behavior can be useful, it is error-prone. In general,8040it is safer to avoid aliasing when you are working with mutable8041objects.8042\index{immutability}80438044For immutable objects like strings, aliasing is not as much of a8045problem. In this example:80468047\begin{verbatim}8048a = 'banana'8049b = 'banana'8050\end{verbatim}8051%8052It almost never makes a difference whether {\tt a} and {\tt b} refer8053to the same string or not.805480558056\section{List arguments}8057\label{list.arguments}8058\index{list!as argument}8059\index{argument}8060\index{argument!list}8061\index{reference}8062\index{parameter}80638064When you pass a list to a function, the function gets a reference to8065the list. If the function modifies the list, the caller sees8066the change. For example, \verb"delete_head" removes the first element8067from a list:80688069\begin{verbatim}8070def delete_head(t):8071del t[0]8072\end{verbatim}8073%8074Here's how it is used:80758076\begin{verbatim}8077>>> letters = ['a', 'b', 'c']8078>>> delete_head(letters)8079>>> letters8080['b', 'c']8081\end{verbatim}8082%8083The parameter {\tt t} and the variable {\tt letters} are8084aliases for the same object. The stack diagram looks like8085Figure~\ref{fig.stack5}.8086\index{stack diagram}8087\index{diagram!stack}80888089\begin{figure}8090\centerline8091{\includegraphics[scale=0.8]{figs/stack5.pdf}}8092\caption{Stack diagram.}8093\label{fig.stack5}8094\end{figure}80958096Since the list is shared by two frames, I drew8097it between them.80988099It is important to distinguish between operations that8100modify lists and operations that create new lists. For8101example, the {\tt append} method modifies a list, but the8102{\tt +} operator creates a new list.8103\index{append method}8104\index{method!append}8105\index{list!concatenation}8106\index{concatenation!list}81078108Here's an example using {\tt append}:8109%8110\begin{verbatim}8111>>> t1 = [1, 2]8112>>> t2 = t1.append(3)8113>>> t18114[1, 2, 3]8115>>> t28116None8117\end{verbatim}8118%8119The return value from {\tt append} is {\tt None}.81208121Here's an example using the {\tt +} operator:8122%8123\begin{verbatim}8124>>> t3 = t1 + [4]8125>>> t18126[1, 2, 3]8127>>> t38128[1, 2, 3, 4]8129\end{verbatim}8130%8131The result of the operator is a new list, and the original list is8132unchanged.81338134This difference is important when you write functions that8135are supposed to modify lists. For example, this function8136{\em does not} delete the head of a list:8137%8138\begin{verbatim}8139def bad_delete_head(t):8140t = t[1:] # WRONG!8141\end{verbatim}8142%8143The slice operator creates a new list and the assignment8144makes {\tt t} refer to it, but that doesn't affect the caller.8145\index{slice operator}8146\index{operator!slice}8147%8148\begin{verbatim}8149>>> t4 = [1, 2, 3]8150>>> bad_delete_head(t4)8151>>> t48152[1, 2, 3]8153\end{verbatim}8154%8155At the beginning of \verb"bad_delete_head", {\tt t} and {\tt t4}8156refer to the same list. At the end, {\tt t} refers to a new list,8157but {\tt t4} still refers to the original, unmodified list.81588159An alternative is to write a function that creates and8160returns a new list. For8161example, {\tt tail} returns all but the first8162element of a list:81638164\begin{verbatim}8165def tail(t):8166return t[1:]8167\end{verbatim}8168%8169This function leaves the original list unmodified.8170Here's how it is used:81718172\begin{verbatim}8173>>> letters = ['a', 'b', 'c']8174>>> rest = tail(letters)8175>>> rest8176['b', 'c']8177\end{verbatim}8178817981808181\section{Debugging}8182\index{debugging}81838184Careless use of lists (and other mutable objects)8185can lead to long hours of debugging. Here are some common8186pitfalls and ways to avoid them:81878188\begin{enumerate}81898190\item Most list methods modify the argument and8191return {\tt None}. This is the opposite of the string methods,8192which return a new string and leave the original alone.81938194If you are used to writing string code like this:81958196\begin{verbatim}8197word = word.strip()8198\end{verbatim}81998200It is tempting to write list code like this:82018202\begin{verbatim}8203t = t.sort() # WRONG!8204\end{verbatim}8205\index{sort method}8206\index{method!sort}82078208Because {\tt sort} returns {\tt None}, the8209next operation you perform with {\tt t} is likely to fail.82108211Before using list methods and operators, you should read the8212documentation carefully and then test them in interactive mode.82138214\item Pick an idiom and stick with it.82158216Part of the problem with lists is that there are too many8217ways to do things. For example, to remove an element from8218a list, you can use {\tt pop}, {\tt remove}, {\tt del},8219or even a slice assignment.82208221To add an element, you can use the {\tt append} method or8222the {\tt +} operator. Assuming that {\tt t} is a list and8223{\tt x} is a list element, these are correct:82248225\begin{verbatim}8226t.append(x)8227t = t + [x]8228t += [x]8229\end{verbatim}82308231And these are wrong:82328233\begin{verbatim}8234t.append([x]) # WRONG!8235t = t.append(x) # WRONG!8236t + [x] # WRONG!8237t = t + x # WRONG!8238\end{verbatim}82398240Try out each of these examples in interactive mode to make sure8241you understand what they do. Notice that only the last8242one causes a runtime error; the other three are legal, but they8243do the wrong thing.824482458246\item Make copies to avoid aliasing.8247\index{aliasing!copying to avoid}8248\index{copy!to avoid aliasing}82498250If you want to use a method like {\tt sort} that modifies8251the argument, but you need to keep the original list as8252well, you can make a copy.82538254\begin{verbatim}8255>>> t = [3, 1, 2]8256>>> t2 = t[:]8257>>> t2.sort()8258>>> t8259[3, 1, 2]8260>>> t28261[1, 2, 3]8262\end{verbatim}82638264In this example you could also use the built-in function {\tt sorted},8265which returns a new, sorted list and leaves the original alone.8266\index{sorted!function}8267\index{function!sorted}82688269\begin{verbatim}8270>>> t2 = sorted(t)8271>>> t8272[3, 1, 2]8273>>> t28274[1, 2, 3]8275\end{verbatim}82768277\end{enumerate}8278827982808281\section{Glossary}82828283\begin{description}82848285\item[list:] A sequence of values.8286\index{list}82878288\item[element:] One of the values in a list (or other sequence),8289also called items.8290\index{element}82918292\item[nested list:] A list that is an element of another list.8293\index{nested list}82948295\item[accumulator:] A variable used in a loop to add up or8296accumulate a result.8297\index{accumulator}82988299\item[augmented assignment:] A statement that updates the value8300of a variable using an operator like \verb"+=".8301\index{assignment!augmented}8302\index{augmented assignment}8303\index{traversal}83048305\item[reduce:] A processing pattern that traverses a sequence8306and accumulates the elements into a single result.8307\index{reduce pattern}8308\index{pattern!reduce}83098310\item[map:] A processing pattern that traverses a sequence and8311performs an operation on each element.8312\index{map pattern}8313\index{pattern!map}83148315\item[filter:] A processing pattern that traverses a list and8316selects the elements that satisfy some criterion.8317\index{filter pattern}8318\index{pattern!filter}83198320\item[object:] Something a variable can refer to. An object8321has a type and a value.8322\index{object}83238324\item[equivalent:] Having the same value.8325\index{equivalent}83268327\item[identical:] Being the same object (which implies equivalence).8328\index{identical}83298330\item[reference:] The association between a variable and its value.8331\index{reference}83328333\item[aliasing:] A circumstance where two or more variables refer to the same8334object.8335\index{aliasing}83368337\item[delimiter:] A character or string used to indicate where a8338string should be split.8339\index{delimiter}83408341\end{description}834283438344\section{Exercises}83458346You can download solutions to these exercises from8347\url{http://thinkpython2.com/code/list_exercises.py}.83488349\begin{exercise}83508351Write a function called \verb"nested_sum" that takes a list of lists8352of integers and adds up the elements from all of the nested lists.8353For example:83548355\begin{verbatim}8356>>> t = [[1, 2], [3], [4, 5, 6]]8357>>> nested_sum(t)8358218359\end{verbatim}83608361\end{exercise}83628363\begin{exercise}8364\label{cumulative}8365\index{cumulative sum}83668367Write a function called {\tt cumsum} that takes a list of numbers and8368returns the cumulative sum; that is, a new list where the $i$th8369element is the sum of the first $i+1$ elements from the original list.8370For example:83718372\begin{verbatim}8373>>> t = [1, 2, 3]8374>>> cumsum(t)8375[1, 3, 6]8376\end{verbatim}83778378\end{exercise}83798380\begin{exercise}83818382Write a function called \verb"middle" that takes a list and8383returns a new list that contains all but the first and last8384elements. For example:83858386\begin{verbatim}8387>>> t = [1, 2, 3, 4]8388>>> middle(t)8389[2, 3]8390\end{verbatim}83918392\end{exercise}83938394\begin{exercise}83958396Write a function called \verb"chop" that takes a list, modifies it8397by removing the first and last elements, and returns {\tt None}.8398For example:83998400\begin{verbatim}8401>>> t = [1, 2, 3, 4]8402>>> chop(t)8403>>> t8404[2, 3]8405\end{verbatim}84068407\end{exercise}840884098410\begin{exercise}8411Write a function called \verb"is_sorted" that takes a list as a8412parameter and returns {\tt True} if the list is sorted in ascending8413order and {\tt False} otherwise. For example:84148415\begin{verbatim}8416>>> is_sorted([1, 2, 2])8417True8418>>> is_sorted(['b', 'a'])8419False8420\end{verbatim}84218422\end{exercise}842384248425\begin{exercise}8426\label{anagram}8427\index{anagram}84288429Two words are anagrams if you can rearrange the letters from one8430to spell the other. Write a function called \verb"is_anagram"8431that takes two strings and returns {\tt True} if they are anagrams.8432\end{exercise}8433843484358436\begin{exercise}8437\label{duplicate}8438\index{duplicate}8439\index{uniqueness}84408441Write a function called \verb"has_duplicates" that takes8442a list and returns {\tt True} if there is any element that8443appears more than once. It should not modify the original8444list.84458446\end{exercise}844784488449\begin{exercise}84508451This exercise pertains to the so-called Birthday Paradox, which you8452can read about at \url{http://en.wikipedia.org/wiki/Birthday_paradox}.8453\index{birthday paradox}84548455If there are 23 students in your class, what are the chances8456that two of you have the same birthday? You can estimate this8457probability by generating random samples of 23 birthdays8458and checking for matches. Hint: you can generate random birthdays8459with the {\tt randint} function in the {\tt random} module.8460\index{random module}8461\index{module!random}8462\index{randint function}8463\index{function!randint}84648465You can download my8466solution from \url{http://thinkpython2.com/code/birthday.py}.84678468\end{exercise}8469847084718472\begin{exercise}8473\index{append method}8474\index{method append}8475\index{list!concatenation}8476\index{concatenation!list}84778478Write a function that reads the file {\tt words.txt} and builds8479a list with one element per word. Write two versions of8480this function, one using the {\tt append} method and the8481other using the idiom {\tt t = t + [x]}. Which one takes8482longer to run? Why?84838484Solution: \url{http://thinkpython2.com/code/wordlist.py}.8485\index{time module}8486\index{module!time}84878488\end{exercise}848984908491\begin{exercise}8492\label{wordlist1}8493\label{bisection}8494\index{membership!bisection search}8495\index{bisection search}8496\index{search, bisection}8497\index{membership!binary search}8498\index{binary search}8499\index{search, binary}85008501To check whether a word is in the word list, you could use8502the {\tt in} operator, but it would be slow because it searches8503through the words in order.85048505Because the words are in alphabetical order, we can speed things up8506with a bisection search (also known as binary search), which is8507similar to what you do when you look a word up in the dictionary (the book, not the data structure). You8508start in the middle and check to see whether the word you are looking8509for comes before the word in the middle of the list. If so, you8510search the first half of the list the same way. Otherwise you search8511the second half.85128513Either way, you cut the remaining search space in half. If the8514word list has 113,809 words, it will take about 17 steps to8515find the word or conclude that it's not there.85168517Write a function called \verb"in_bisect" that takes a sorted list8518and a target value and returns {\tt True} if the word is8519in the list and {\tt False} if it's not.8520\index{bisect module}8521\index{module!bisect}85228523Or you could read the documentation of the {\tt bisect} module8524and use that! Solution: \url{http://thinkpython2.com/code/inlist.py}.85258526\end{exercise}85278528\begin{exercise}8529\index{reverse word pair}85308531Two words are a ``reverse pair'' if each is the reverse of the8532other. Write a program that finds all the reverse pairs in the8533word list. Solution: \url{http://thinkpython2.com/code/reverse_pair.py}.85348535\end{exercise}85368537\begin{exercise}8538\index{interlocking words}85398540Two words ``interlock'' if taking alternating letters from each forms8541a new word. For example, ``shoe'' and ``cold''8542interlock to form ``schooled''.8543Solution: \url{http://thinkpython2.com/code/interlock.py}.8544Credit: This exercise is inspired by an example at \url{http://puzzlers.org}.85458546\begin{enumerate}85478548\item Write a program that finds all pairs of words that interlock.8549Hint: don't enumerate all pairs!85508551\item Can you find any words that are three-way interlocked; that is,8552every third letter forms a word, starting from the first, second or8553third?85548555\end{enumerate}8556\end{exercise}855785588559\chapter{Dictionaries}85608561This chapter presents another built-in type called a dictionary.8562Dictionaries are one of Python's best features; they are the8563building blocks of many efficient and elegant algorithms.856485658566\section{A dictionary is a mapping}85678568\index{dictionary}8569\index{dictionary}8570\index{type!dict}8571\index{key}8572\index{key-value pair}8573\index{index}8574A {\bf dictionary} is like a list, but more general. In a list,8575the indices have to be integers; in a dictionary they can8576be (almost) any type.85778578A dictionary contains a collection of indices, which are called {\bf8579keys}, and a collection of values. Each key is associated with a8580single value. The association of a key and a value is called a {\bf8581key-value pair} or sometimes an {\bf item}. \index{item}85828583In mathematical language, a dictionary represents a {\bf mapping}8584from keys to values, so you can also say that each key8585``maps to'' a value.8586As an example, we'll build a dictionary that maps from English8587to Spanish words, so the keys and the values are all strings.85888589The function {\tt dict} creates a new dictionary with no items.8590Because {\tt dict} is the name of a built-in function, you8591should avoid using it as a variable name.8592\index{dict function}8593\index{function!dict}85948595\begin{verbatim}8596>>> eng2sp = dict()8597>>> eng2sp8598{}8599\end{verbatim}86008601The squiggly-brackets, \verb"{}", represent an empty dictionary.8602To add items to the dictionary, you can use square brackets:8603\index{squiggly bracket}8604\index{bracket!squiggly}86058606\begin{verbatim}8607>>> eng2sp['one'] = 'uno'8608\end{verbatim}8609%8610This line creates an item that maps from the key8611\verb"'one'" to the value \verb"'uno'". If we print the8612dictionary again, we see a key-value pair with a colon8613between the key and value:86148615\begin{verbatim}8616>>> eng2sp8617{'one': 'uno'}8618\end{verbatim}8619%8620This output format is also an input format. For example,8621you can create a new dictionary with three items:86228623\begin{verbatim}8624>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}8625\end{verbatim}8626%8627But if you print {\tt eng2sp}, you might be surprised:86288629\begin{verbatim}8630>>> eng2sp8631{'one': 'uno', 'three': 'tres', 'two': 'dos'}8632\end{verbatim}8633%8634The order of the key-value pairs might not be the same. If8635you type the same example on your computer, you might get a8636different result. In general, the order of items in8637a dictionary is unpredictable.86388639But that's not a problem because8640the elements of a dictionary are never indexed with integer indices.8641Instead, you use the keys to look up the corresponding values:86428643\begin{verbatim}8644>>> eng2sp['two']8645'dos'8646\end{verbatim}8647%8648The key \verb"'two'" always maps to the value \verb"'dos'" so the order8649of the items doesn't matter.86508651If the key isn't in the dictionary, you get an exception:8652\index{exception!KeyError}8653\index{KeyError}86548655\begin{verbatim}8656>>> eng2sp['four']8657KeyError: 'four'8658\end{verbatim}8659%8660The {\tt len} function works on dictionaries; it returns the8661number of key-value pairs:8662\index{len function}8663\index{function!len}86648665\begin{verbatim}8666>>> len(eng2sp)866738668\end{verbatim}8669%8670The {\tt in} operator works on dictionaries, too; it tells you whether8671something appears as a {\em key} in the dictionary (appearing8672as a value is not good enough).8673\index{membership!dictionary}8674\index{in operator}8675\index{operator!in}86768677\begin{verbatim}8678>>> 'one' in eng2sp8679True8680>>> 'uno' in eng2sp8681False8682\end{verbatim}8683%8684To see whether something appears as a value in a dictionary, you8685can use the method {\tt values}, which returns a collection of8686values, and then use the {\tt in} operator:8687\index{values method}8688\index{method!values}86898690\begin{verbatim}8691>>> vals = eng2sp.values()8692>>> 'uno' in vals8693True8694\end{verbatim}8695%8696The {\tt in} operator uses different algorithms for lists and8697dictionaries. For lists, it searches the elements of the list in8698order, as in Section~\ref{find}. As the list gets longer, the search8699time gets longer in direct proportion.87008701Python dictionaries use a data structure8702called a {\bf hashtable} that has a remarkable property: the8703{\tt in} operator takes about the same amount of time no matter how8704many items are in the dictionary. I explain how that's possible8705in Section~\ref{hashtable}, but the explanation might not make8706sense until you've read a few more chapters.870787088709\section{Dictionary as a collection of counters}8710\label{histogram}8711\index{counter}87128713Suppose you are given a string and you want to count how many8714times each letter appears. There are several ways you could do it:87158716\begin{enumerate}87178718\item You could create 26 variables, one for each letter of the8719alphabet. Then you could traverse the string and, for each8720character, increment the corresponding counter, probably using8721a chained conditional.87228723\item You could create a list with 26 elements. Then you could8724convert each character to a number (using the built-in function8725{\tt ord}), use the number as an index into the list, and increment8726the appropriate counter.87278728\item You could create a dictionary with characters as keys8729and counters as the corresponding values. The first time you8730see a character, you would add an item to the dictionary. After8731that you would increment the value of an existing item.87328733\end{enumerate}87348735Each of these options performs the same computation, but each8736of them implements that computation in a different way.8737\index{implementation}87388739An {\bf implementation} is a way of performing a computation;8740some implementations are better than others. For example,8741an advantage of the dictionary implementation is that we don't8742have to know ahead of time which letters appear in the string8743and we only have to make room for the letters that do appear.87448745Here is what the code might look like:87468747\begin{verbatim}8748def histogram(s):8749d = dict()8750for c in s:8751if c not in d:8752d[c] = 18753else:8754d[c] += 18755return d8756\end{verbatim}8757%8758The name of the function is {\tt histogram}, which is a statistical8759term for a collection of counters (or frequencies).8760\index{histogram}8761\index{frequency}8762\index{traversal}87638764The first line of the8765function creates an empty dictionary. The {\tt for} loop traverses8766the string. Each time through the loop, if the character {\tt c} is8767not in the dictionary, we create a new item with key {\tt c} and the8768initial value 1 (since we have seen this letter once). If {\tt c} is8769already in the dictionary we increment {\tt d[c]}.8770\index{histogram}87718772Here's how it works:87738774\begin{verbatim}8775>>> h = histogram('brontosaurus')8776>>> h8777{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}8778\end{verbatim}8779%8780The histogram indicates that the letters \verb"'a'" and \verb"'b'"8781appear once; \verb"'o'" appears twice, and so on.878287838784\index{get method}8785\index{method!get}8786Dictionaries have a method called {\tt get} that takes a key8787and a default value. If the key appears in the dictionary,8788{\tt get} returns the corresponding value; otherwise it returns8789the default value. For example:87908791\begin{verbatim}8792>>> h = histogram('a')8793>>> h8794{'a': 1}8795>>> h.get('a', 0)879618797>>> h.get('c', 0)879808799\end{verbatim}8800%8801As an exercise, use {\tt get} to write {\tt histogram} more concisely. You8802should be able to eliminate the {\tt if} statement.880388048805\section{Looping and dictionaries}8806\index{dictionary!looping with}8807\index{looping!with dictionaries}8808\index{traversal}88098810If you use a dictionary in a {\tt for} statement, it traverses8811the keys of the dictionary. For example, \verb"print_hist"8812prints each key and the corresponding value:88138814\begin{verbatim}8815def print_hist(h):8816for c in h:8817print(c, h[c])8818\end{verbatim}8819%8820Here's what the output looks like:88218822\begin{verbatim}8823>>> h = histogram('parrot')8824>>> print_hist(h)8825a 18826p 18827r 28828t 18829o 18830\end{verbatim}8831%8832Again, the keys are in no particular order. To traverse the keys8833in sorted order, you can use the built-in function {\tt sorted}:8834\index{sorted!function}8835\index{function!sorted}88368837\begin{verbatim}8838>>> for key in sorted(h):8839... print(key, h[key])8840a 18841o 18842p 18843r 28844t 18845\end{verbatim}88468847%TODO: get this on Atlas884888498850\section{Reverse lookup}8851\label{raise}8852\index{dictionary!lookup}8853\index{dictionary!reverse lookup}8854\index{lookup, dictionary}8855\index{reverse lookup, dictionary}88568857Given a dictionary {\tt d} and a key {\tt k}, it is easy to8858find the corresponding value {\tt v = d[k]}. This operation8859is called a {\bf lookup}.88608861But what if you have {\tt v} and you want to find {\tt k}?8862You have two problems: first, there might be more than one8863key that maps to the value {\tt v}. Depending on the application,8864you might be able to pick one, or you might have to make8865a list that contains all of them. Second, there is no8866simple syntax to do a {\bf reverse lookup}; you have to search.88678868Here is a function that takes a value and returns the first8869key that maps to that value:88708871\begin{verbatim}8872def reverse_lookup(d, v):8873for k in d:8874if d[k] == v:8875return k8876raise LookupError()8877\end{verbatim}8878%8879This function is yet another example of the search pattern, but it8880uses a feature we haven't seen before, {\tt raise}. The8881{\bf raise statement} causes an exception; in this case it causes a8882{\tt LookupError}, which is a built-in exception used to indicate8883that a lookup operation failed.8884\index{search}8885\index{pattern!search} \index{raise statement} \index{statement!raise}8886\index{exception!LookupError} \index{LookupError}88878888If we get to the end of the loop, that means {\tt v}8889doesn't appear in the dictionary as a value, so we raise an8890exception.88918892Here is an example of a successful reverse lookup:88938894\begin{verbatim}8895>>> h = histogram('parrot')8896>>> key = reverse_lookup(h, 2)8897>>> key8898'r'8899\end{verbatim}8900%8901And an unsuccessful one:89028903\begin{verbatim}8904>>> key = reverse_lookup(h, 3)8905Traceback (most recent call last):8906File "<stdin>", line 1, in <module>8907File "<stdin>", line 5, in reverse_lookup8908LookupError8909\end{verbatim}8910%8911The effect when you raise an exception is the same as when8912Python raises one: it prints a traceback and an error message.8913\index{traceback}8914\index{optional argument}8915\index{argument!optional}89168917When you raise an exception, you can provide a detailed error message as an optional argument. For example:89188919\begin{verbatim}8920>>> raise LookupError('value does not appear in the dictionary')8921Traceback (most recent call last):8922File "<stdin>", line 1, in ?8923LookupError: value does not appear in the dictionary8924\end{verbatim}8925%8926A reverse lookup is much slower than a forward lookup; if you8927have to do it often, or if the dictionary gets big, the performance8928of your program will suffer.892989308931\section{Dictionaries and lists}8932\label{invert}89338934Lists can appear as values in a dictionary. For example, if you8935are given a dictionary that maps from letters to frequencies, you8936might want to invert it; that is, create a dictionary that maps8937from frequencies to letters. Since there might be several letters8938with the same frequency, each value in the inverted dictionary8939should be a list of letters.8940\index{invert dictionary}8941\index{dictionary!invert}89428943Here is a function that inverts a dictionary:89448945\begin{verbatim}8946def invert_dict(d):8947inverse = dict()8948for key in d:8949val = d[key]8950if val not in inverse:8951inverse[val] = [key]8952else:8953inverse[val].append(key)8954return inverse8955\end{verbatim}8956%8957Each time through the loop, {\tt key} gets a key from {\tt d} and8958{\tt val} gets the corresponding value. If {\tt val} is not in {\tt8959inverse}, that means we haven't seen it before, so we create a new8960item and initialize it with a {\bf singleton} (a list that contains a8961single element). Otherwise we have seen this value before, so we8962append the corresponding key to the list. \index{singleton}89638964Here is an example:89658966\begin{verbatim}8967>>> hist = histogram('parrot')8968>>> hist8969{'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1}8970>>> inverse = invert_dict(hist)8971>>> inverse8972{1: ['a', 'p', 't', 'o'], 2: ['r']}8973\end{verbatim}89748975\begin{figure}8976\centerline8977{\includegraphics[scale=0.8]{figs/dict1.pdf}}8978\caption{State diagram.}8979\label{fig.dict1}8980\end{figure}89818982Figure~\ref{fig.dict1} is a state diagram showing {\tt hist} and {\tt inverse}.8983A dictionary is represented as a box with the type {\tt dict} above it8984and the key-value pairs inside. If the values are integers, floats or8985strings, I draw them inside the box, but I usually draw lists8986outside the box, just to keep the diagram simple.8987\index{state diagram}8988\index{diagram!state}89898990Lists can be values in a dictionary, as this example shows, but they8991cannot be keys. Here's what happens if you try:8992\index{TypeError}8993\index{exception!TypeError}899489958996\begin{verbatim}8997>>> t = [1, 2, 3]8998>>> d = dict()8999>>> d[t] = 'oops'9000Traceback (most recent call last):9001File "<stdin>", line 1, in ?9002TypeError: list objects are unhashable9003\end{verbatim}9004%9005I mentioned earlier that a dictionary is implemented using9006a hashtable and that means that the keys have to be {\bf hashable}.9007\index{hash function}9008\index{hashable}90099010A {\bf hash} is a function that takes a value (of any kind)9011and returns an integer. Dictionaries use these integers,9012called hash values, to store and look up key-value pairs.9013\index{immutability}90149015This system works fine if the keys are immutable. But if the9016keys are mutable, like lists, bad things happen. For example,9017when you create a key-value pair, Python hashes the key and9018stores it in the corresponding location. If you modify the9019key and then hash it again, it would go to a different location.9020In that case you might have two entries for the same key,9021or you might not be able to find a key. Either way, the9022dictionary wouldn't work correctly.90239024That's why keys have to be hashable, and why mutable types like9025lists aren't. The simplest way to get around this limitation is to9026use tuples, which we will see in the next chapter.90279028Since dictionaries are mutable, they can't be used as keys,9029but they {\em can} be used as values.903090319032\section{Memos}9033\label{memoize}90349035If you played with the {\tt fibonacci} function from9036Section~\ref{one.more.example}, you might have noticed that the bigger9037the argument you provide, the longer the function takes to run.9038Furthermore, the run time increases quickly.9039\index{fibonacci function}9040\index{function!fibonacci}90419042To understand why, consider Figure~\ref{fig.fibonacci}, which shows9043the {\bf call graph} for {\tt fibonacci} with {\tt n=4}:90449045\begin{figure}9046\centerline9047{\includegraphics[scale=0.7]{figs/fibonacci.pdf}}9048\caption{Call graph.}9049\label{fig.fibonacci}9050\end{figure}90519052A call graph shows a set of function frames, with lines connecting each9053frame to the frames of the functions it calls. At the top of the9054graph, {\tt fibonacci} with {\tt n=4} calls {\tt fibonacci} with {\tt9055n=3} and {\tt n=2}. In turn, {\tt fibonacci} with {\tt n=3} calls9056{\tt fibonacci} with {\tt n=2} and {\tt n=1}. And so on.9057\index{function frame}9058\index{frame}9059\index{call graph}90609061Count how many times {\tt fibonacci(0)} and {\tt fibonacci(1)} are9062called. This is an inefficient solution to the problem, and it gets9063worse as the argument gets bigger.9064\index{memo}90659066One solution is to keep track of values that have already been9067computed by storing them in a dictionary. A previously computed value9068that is stored for later use is called a {\bf memo}. Here is a9069``memoized'' version of {\tt fibonacci}:90709071\begin{verbatim}9072known = {0:0, 1:1}90739074def fibonacci(n):9075if n in known:9076return known[n]90779078res = fibonacci(n-1) + fibonacci(n-2)9079known[n] = res9080return res9081\end{verbatim}9082%9083{\tt known} is a dictionary that keeps track of the Fibonacci9084numbers we already know. It starts with9085two items: 0 maps to 0 and 1 maps to 1.90869087Whenever {\tt fibonacci} is called, it checks {\tt known}.9088If the result is already there, it can return9089immediately. Otherwise it has to9090compute the new value, add it to the dictionary, and return it.90919092If you run this version of {\tt fibonacci} and compare it with9093the original, you will find that it is much faster.9094909590969097\section{Global variables}9098\index{global variable}9099\index{variable!global}91009101In the previous example, {\tt known} is created outside the function,9102so it belongs to the special frame called \verb"__main__".9103Variables in \verb"__main__" are sometimes called {\bf global}9104because they can be accessed from any function. Unlike local9105variables, which disappear when their function ends, global variables9106persist from one function call to the next.9107\index{flag}9108\index{main}91099110It is common to use global variables for {\bf flags}; that is,9111boolean variables that indicate (``flag'') whether a condition9112is true. For example, some programs use9113a flag named {\tt verbose} to control the level of detail in the9114output:91159116\begin{verbatim}9117verbose = True91189119def example1():9120if verbose:9121print('Running example1')9122\end{verbatim}9123%9124If you try to reassign a global variable, you might be surprised.9125The following example is supposed to keep track of whether the9126function has been called:9127\index{reassignment}91289129\begin{verbatim}9130been_called = False91319132def example2():9133been_called = True # WRONG9134\end{verbatim}9135%9136But if you run it you will see that the value of \verb"been_called"9137doesn't change. The problem is that {\tt example2} creates a new local9138variable named \verb"been_called". The local variable goes away when9139the function ends, and has no effect on the global variable.9140\index{global statement}9141\index{statement!global}9142\index{declaration}91439144To reassign a global variable inside a function you have to9145{\bf declare} the global variable before you use it:91469147\begin{verbatim}9148been_called = False91499150def example2():9151global been_called9152been_called = True9153\end{verbatim}9154%9155The {\bf global statement} tells the interpreter9156something like, ``In this function, when I say \verb"been_called", I9157mean the global variable; don't create a local one.''9158\index{update!global variable}9159\index{global variable!update}91609161Here's an example that tries to update a global variable:91629163\begin{verbatim}9164count = 091659166def example3():9167count = count + 1 # WRONG9168\end{verbatim}9169%9170If you run it you get:9171\index{UnboundLocalError}9172\index{exception!UnboundLocalError}91739174\begin{verbatim}9175UnboundLocalError: local variable 'count' referenced before assignment9176\end{verbatim}9177%9178Python assumes that {\tt count} is local, and under that assumption9179you are reading it before writing it. The solution, again,9180is to declare {\tt count} global.9181\index{counter}91829183\begin{verbatim}9184def example3():9185global count9186count += 19187\end{verbatim}9188%9189If a global variable refers to a mutable value, you can modify9190the value without declaring the variable:9191\index{mutability}91929193\begin{verbatim}9194known = {0:0, 1:1}91959196def example4():9197known[2] = 19198\end{verbatim}9199%9200So you can add, remove and replace elements of a global list or9201dictionary, but if you want to reassign the variable, you9202have to declare it:92039204\begin{verbatim}9205def example5():9206global known9207known = dict()9208\end{verbatim}9209%9210Global variables can be useful, but if you have a lot of them,9211and you modify them frequently, they can make programs9212hard to debug.921392149215\section{Debugging}9216\index{debugging}92179218As you work with bigger datasets it can become unwieldy to9219debug by printing and checking the output by hand. Here are some9220suggestions for debugging large datasets:92219222\begin{description}92239224\item[Scale down the input:] If possible, reduce the size of the9225dataset. For example if the program reads a text file, start with9226just the first 10 lines, or with the smallest example you can find.9227You can either edit the files themselves, or (better) modify the9228program so it reads only the first {\tt n} lines.92299230If there is an error, you can reduce {\tt n} to the smallest9231value that manifests the error, and then increase it gradually9232as you find and correct errors.92339234\item[Check summaries and types:] Instead of printing and checking the9235entire dataset, consider printing summaries of the data: for example,9236the number of items in a dictionary or the total of a list of numbers.92379238A common cause of runtime errors is a value that is not the right9239type. For debugging this kind of error, it is often enough to print9240the type of a value.92419242\item[Write self-checks:] Sometimes you can write code to check9243for errors automatically. For example, if you are computing the9244average of a list of numbers, you could check that the result is9245not greater than the largest element in the list or less than9246the smallest. This is called a ``sanity check'' because it detects9247results that are ``insane''.9248\index{sanity check}9249\index{consistency check}92509251Another kind of check compares the results of two different9252computations to see if they are consistent. This is called a9253``consistency check''.92549255\item[Format the output:] Formatting debugging output9256can make it easier to spot an error. We saw an example in9257Section~\ref{factdebug}. Another tool you might find useful is the {\tt pprint} module, which provides9258a {\tt pprint} function that displays built-in types in9259a more human-readable format ({\tt pprint} stands for9260``pretty print'').9261\index{pretty print}9262\index{pprint module}9263\index{module!pprint}92649265\end{description}92669267Again, time you spend building scaffolding can reduce9268the time you spend debugging.9269\index{scaffolding}927092719272\section{Glossary}92739274\begin{description}92759276\item[mapping:] A relationship in which each element of one set9277corresponds to an element of another set.9278\index{mapping}92799280\item[dictionary:] A mapping from keys to their9281corresponding values.9282\index{dictionary}92839284\item[key-value pair:] The representation of the mapping from9285a key to a value.9286\index{key-value pair}92879288\item[item:] In a dictionary, another name for a key-value9289pair.9290\index{item!dictionary}92919292\item[key:] An object that appears in a dictionary as the9293first part of a key-value pair.9294\index{key}92959296\item[value:] An object that appears in a dictionary as the9297second part of a key-value pair. This is more specific than9298our previous use of the word ``value''.9299\index{value}93009301\item[implementation:] A way of performing a computation.9302\index{implementation}93039304\item[hashtable:] The algorithm used to implement Python9305dictionaries.9306\index{hashtable}93079308\item[hash function:] A function used by a hashtable to compute the9309location for a key.9310\index{hash function}93119312\item[hashable:] A type that has a hash function. Immutable9313types like integers,9314floats and strings are hashable; mutable types like lists and9315dictionaries are not.9316\index{hashable}93179318\item[lookup:] A dictionary operation that takes a key and finds9319the corresponding value.9320\index{lookup}93219322\item[reverse lookup:] A dictionary operation that takes a value and finds9323one or more keys that map to it.9324\index{reverse lookup}93259326\item[raise statement:] A statement that (deliberately) raises an exception.9327\index{raise statement}9328\index{statement!raise}93299330\item[singleton:] A list (or other sequence) with a single element.9331\index{singleton}93329333\item[call graph:] A diagram that shows every frame created during9334the execution of a program, with an arrow from each caller to9335each callee.9336\index{call graph}9337\index{diagram!call graph}93389339\item[memo:] A computed value stored to avoid unnecessary future9340computation.9341\index{memo}93429343\item[global variable:] A variable defined outside a function. Global9344variables can be accessed from any function.9345\index{global variable}93469347\item[global statement:] A statement that declares a variable name9348global.9349\index{global statement}9350\index{statement!global}93519352\item[flag:] A boolean variable used to indicate whether a condition9353is true.9354\index{flag}93559356\item[declaration:] A statement like {\tt global} that tells the9357interpreter something about a variable.9358\index{declaration}93599360\end{description}936193629363\section{Exercises}93649365\begin{exercise}9366\label{wordlist2}9367\index{set membership}9368\index{membership!set}93699370Write a function that reads the words in {\tt words.txt} and9371stores them as keys in a dictionary. It doesn't matter what the9372values are. Then you can use the {\tt in} operator9373as a fast way to check whether a string is in9374the dictionary.93759376If you did Exercise~\ref{wordlist1}, you can compare the speed9377of this implementation with the list {\tt in} operator and the9378bisection search.93799380\end{exercise}938193829383\begin{exercise}9384\label{setdefault}93859386Read the documentation of the dictionary method {\tt setdefault}9387and use it to write a more concise version of \verb"invert_dict".9388Solution: \url{http://thinkpython2.com/code/invert_dict.py}.9389\index{setdefault method}9390\index{method!setdefault}93919392\end{exercise}939393949395\begin{exercise}9396Memoize the Ackermann function from Exercise~\ref{ackermann} and see if9397memoization makes it possible to evaluate the function with bigger9398arguments. Hint: no.9399Solution: \url{http://thinkpython2.com/code/ackermann_memo.py}.9400\index{Ackermann function}9401\index{function!ack}94029403\end{exercise}9404940594069407\begin{exercise}9408\index{duplicate}94099410If you did Exercise~\ref{duplicate}, you already have9411a function named \verb"has_duplicates" that takes a list9412as a parameter and returns {\tt True} if there is any object9413that appears more than once in the list.94149415Use a dictionary to write a faster, simpler version of9416\verb"has_duplicates".9417Solution: \url{http://thinkpython2.com/code/has_duplicates.py}.94189419\end{exercise}942094219422\begin{exercise}9423\label{exrotatepairs}9424\index{letter rotation}9425\index{rotation!letters}94269427Two words are ``rotate pairs'' if you can rotate one of them9428and get the other (see \verb"rotate_word" in Exercise~\ref{exrotate}).94299430Write a program that reads a wordlist and finds all the rotate9431pairs. Solution: \url{http://thinkpython2.com/code/rotate_pairs.py}.94329433\end{exercise}943494359436\begin{exercise}9437\index{Car Talk}9438\index{Puzzler}94399440Here's another Puzzler from {\em Car Talk}9441(\url{http://www.cartalk.com/content/puzzlers}):94429443\begin{quote}9444This was sent in by a fellow named Dan O'Leary. He came upon a common9445one-syllable, five-letter word recently that has the following unique9446property. When you remove the first letter, the remaining letters form9447a homophone of the original word, that is a word that sounds exactly9448the same. Replace the first letter, that is, put it back and remove9449the second letter and the result is yet another homophone of the9450original word. And the question is, what's the word?94519452Now I'm going to give you an example that doesn't work. Let's look at9453the five-letter word, `wrack.' W-R-A-C-K, you know like to `wrack with9454pain.' If I remove the first letter, I am left with a four-letter9455word, 'R-A-C-K.' As in, `Holy cow, did you see the rack on that buck!9456It must have been a nine-pointer!' It's a perfect homophone. If you9457put the `w' back, and remove the `r,' instead, you're left with the9458word, `wack,' which is a real word, it's just not a homophone of the9459other two words.94609461But there is, however, at least one word that Dan and we know of,9462which will yield two homophones if you remove either of the first two9463letters to make two, new four-letter words. The question is, what's9464the word?9465\end{quote}9466\index{homophone}9467\index{reducible word}9468\index{word, reducible}94699470You can use the dictionary from Exercise~\ref{wordlist2} to check9471whether a string is in the word list.94729473To check whether two words are homophones, you can use the CMU9474Pronouncing Dictionary. You can download it from9475\url{http://www.speech.cs.cmu.edu/cgi-bin/cmudict} or from9476\url{http://thinkpython2.com/code/c06d} and you can also download9477\url{http://thinkpython2.com/code/pronounce.py}, which provides a function9478named \verb"read_dictionary" that reads the pronouncing dictionary and9479returns a Python dictionary that maps from each word to a string that9480describes its primary pronunciation.94819482Write a program that lists all the words that solve the Puzzler.9483Solution: \url{http://thinkpython2.com/code/homophone.py}.94849485\end{exercise}9486948794889489\chapter{Tuples}9490\label{tuplechap}94919492This chapter presents one more built-in type, the tuple, and then9493shows how lists, dictionaries, and tuples work together.9494I also present a useful feature for variable-length argument lists,9495the gather and scatter operators.94969497One note: there is no consensus on how to pronounce ``tuple''.9498Some people say ``tuh-ple'', which rhymes with ``supple''. But9499in the context of programming, most people say ``too-ple'', which9500rhymes with ``quadruple''.950195029503\section{Tuples are immutable}9504\index{tuple}9505\index{type!tuple}9506\index{sequence}95079508A tuple is a sequence of values. The values can be any type, and9509they are indexed by integers, so in that respect tuples are a lot9510like lists. The important difference is that tuples are immutable.9511\index{mutability}9512\index{immutability}95139514Syntactically, a tuple is a comma-separated list of values:95159516\begin{verbatim}9517>>> t = 'a', 'b', 'c', 'd', 'e'9518\end{verbatim}9519%9520Although it is not necessary, it is common to enclose tuples in9521parentheses:9522\index{parentheses!tuples in}95239524\begin{verbatim}9525>>> t = ('a', 'b', 'c', 'd', 'e')9526\end{verbatim}9527%9528To create a tuple with a single element, you have to include a final9529comma:9530\index{singleton}9531\index{tuple!singleton}95329533\begin{verbatim}9534>>> t1 = 'a',9535>>> type(t1)9536<class 'tuple'>9537\end{verbatim}9538%9539A value in parentheses is not a tuple:95409541\begin{verbatim}9542>>> t2 = ('a')9543>>> type(t2)9544<class 'str'>9545\end{verbatim}9546%9547Another way to create a tuple is the built-in function {\tt tuple}.9548With no argument, it creates an empty tuple:9549\index{tuple function}9550\index{function!tuple}95519552\begin{verbatim}9553>>> t = tuple()9554>>> t9555()9556\end{verbatim}9557%9558If the argument is a sequence (string, list or tuple), the result9559is a tuple with the elements of the sequence:95609561\begin{verbatim}9562>>> t = tuple('lupins')9563>>> t9564('l', 'u', 'p', 'i', 'n', 's')9565\end{verbatim}9566%9567Because {\tt tuple} is the name of a built-in function, you should9568avoid using it as a variable name.95699570Most list operators also work on tuples. The bracket operator9571indexes an element:9572\index{bracket operator}9573\index{operator!bracket}95749575\begin{verbatim}9576>>> t = ('a', 'b', 'c', 'd', 'e')9577>>> t[0]9578'a'9579\end{verbatim}9580%9581And the slice operator selects a range of elements.9582\index{slice operator}9583\index{operator!slice}9584\index{tuple!slice}9585\index{slice!tuple}95869587\begin{verbatim}9588>>> t[1:3]9589('b', 'c')9590\end{verbatim}9591%9592But if you try to modify one of the elements of the tuple, you get9593an error:9594\index{exception!TypeError}9595\index{TypeError}9596\index{item assignment}9597\index{assignment!item}95989599\begin{verbatim}9600>>> t[0] = 'A'9601TypeError: object doesn't support item assignment9602\end{verbatim}9603%9604Because tuples are immutable, you can't modify the elements. But you9605can replace one tuple with another:96069607\begin{verbatim}9608>>> t = ('A',) + t[1:]9609>>> t9610('A', 'b', 'c', 'd', 'e')9611\end{verbatim}9612%9613This statement makes a new tuple and then makes {\tt t} refer to it.96149615The relational operators work with tuples and other sequences;9616Python starts by comparing the first element from each9617sequence. If they are equal, it goes on to the next elements,9618and so on, until it finds elements that differ. Subsequent9619elements are not considered (even if they are really big).9620\index{comparison!tuple}9621\index{tuple!comparison}96229623\begin{verbatim}9624>>> (0, 1, 2) < (0, 3, 4)9625True9626>>> (0, 1, 2000000) < (0, 3, 4)9627True9628\end{verbatim}9629963096319632\section{Tuple assignment}9633\label{tuple.assignment}9634\index{tuple!assignment}9635\index{assignment!tuple}9636\index{swap pattern}9637\index{pattern!swap}96389639It is often useful to swap the values of two variables.9640With conventional assignments, you have to use a temporary9641variable. For example, to swap {\tt a} and {\tt b}:96429643\begin{verbatim}9644>>> temp = a9645>>> a = b9646>>> b = temp9647\end{verbatim}9648%9649This solution is cumbersome; {\bf tuple assignment} is more elegant:96509651\begin{verbatim}9652>>> a, b = b, a9653\end{verbatim}9654%9655The left side is a tuple of variables; the right side is a tuple of9656expressions. Each value is assigned to its respective variable.9657All the expressions on the right side are evaluated before any9658of the assignments.96599660The number of variables on the left and the number of9661values on the right have to be the same:9662\index{exception!ValueError}9663\index{ValueError}96649665\begin{verbatim}9666>>> a, b = 1, 2, 39667ValueError: too many values to unpack9668\end{verbatim}9669%9670More generally, the right side can be any kind of sequence9671(string, list or tuple). For example, to split an email address9672into a user name and a domain, you could write:9673\index{split method}9674\index{method!split}9675\index{email address}96769677\begin{verbatim}9678>>> addr = 'monty@python.org'9679>>> uname, domain = addr.split('@')9680\end{verbatim}9681%9682The return value from {\tt split} is a list with two elements;9683the first element is assigned to {\tt uname}, the second to9684{\tt domain}.96859686\begin{verbatim}9687>>> uname9688'monty'9689>>> domain9690'python.org'9691\end{verbatim}9692%96939694\section{Tuples as return values}9695\index{tuple}9696\index{value!tuple}9697\index{return value!tuple}9698\index{function!tuple as return value}96999700Strictly speaking, a function can only return one value, but9701if the value is a tuple, the effect is the same as returning9702multiple values. For example, if you want to divide two integers9703and compute the quotient and remainder, it is inefficient to9704compute {\tt x//y} and then {\tt x\%y}. It is better to compute9705them both at the same time.9706\index{divmod}97079708The built-in function {\tt divmod} takes two arguments and9709returns a tuple of two values, the quotient and remainder.9710You can store the result as a tuple:97119712\begin{verbatim}9713>>> t = divmod(7, 3)9714>>> t9715(2, 1)9716\end{verbatim}9717%9718Or use tuple assignment to store the elements separately:9719\index{tuple assignment}9720\index{assignment!tuple}97219722\begin{verbatim}9723>>> quot, rem = divmod(7, 3)9724>>> quot972529726>>> rem972719728\end{verbatim}9729%9730Here is an example of a function that returns a tuple:97319732\begin{verbatim}9733def min_max(t):9734return min(t), max(t)9735\end{verbatim}9736%9737{\tt max} and {\tt min} are built-in functions that find9738the largest and smallest elements of a sequence. \verb"min_max"9739computes both and returns a tuple of two values.9740\index{max function}9741\index{function!max}9742\index{min function}9743\index{function!min}974497459746\section{Variable-length argument tuples}9747\label{gather}9748\index{variable-length argument tuple}9749\index{argument!variable-length tuple}9750\index{gather}9751\index{parameter!gather}9752\index{argument!gather}97539754Functions can take a variable number of arguments. A parameter9755name that begins with {\tt *} {\bf gathers} arguments into9756a tuple. For example, {\tt printall}9757takes any number of arguments and prints them:97589759\begin{verbatim}9760def printall(*args):9761print(args)9762\end{verbatim}9763%9764The gather parameter can have any name you like, but {\tt args} is9765conventional. Here's how the function works:97669767\begin{verbatim}9768>>> printall(1, 2.0, '3')9769(1, 2.0, '3')9770\end{verbatim}9771%9772The complement of gather is {\bf scatter}. If you have a9773sequence of values and you want to pass it to a function9774as multiple arguments, you can use the {\tt *} operator.9775For example, {\tt divmod} takes exactly two arguments; it9776doesn't work with a tuple:9777\index{scatter}9778\index{argument scatter}9779\index{TypeError}9780\index{exception!TypeError}97819782\begin{verbatim}9783>>> t = (7, 3)9784>>> divmod(t)9785TypeError: divmod expected 2 arguments, got 19786\end{verbatim}9787%9788But if you scatter the tuple, it works:97899790\begin{verbatim}9791>>> divmod(*t)9792(2, 1)9793\end{verbatim}9794%9795Many of the built-in functions use9796variable-length argument tuples. For example, {\tt max}9797and {\tt min} can take any number of arguments:9798\index{max function}9799\index{function!max}9800\index{min function}9801\index{function!min}98029803\begin{verbatim}9804>>> max(1, 2, 3)980539806\end{verbatim}9807%9808But {\tt sum} does not.9809\index{sum function}9810\index{function!sum}98119812\begin{verbatim}9813>>> sum(1, 2, 3)9814TypeError: sum expected at most 2 arguments, got 39815\end{verbatim}9816%9817As an exercise, write a function called \verb"sum_all" that takes any number9818of arguments and returns their sum.981998209821\section{Lists and tuples}9822\index{zip function}9823\index{function!zip}98249825{\tt zip} is a built-in function that takes two or more sequences and9826interleaves them. The name of the function refers to9827a zipper, which interleaves two rows of teeth.98289829This example zips a string and a list:98309831\begin{verbatim}9832>>> s = 'abc'9833>>> t = [0, 1, 2]9834>>> zip(s, t)9835<zip object at 0x7f7d0a9e7c48>9836\end{verbatim}9837%9838The result is a {\bf zip object} that knows how to iterate through9839the pairs. The most common use of {\tt zip} is in a {\tt for} loop:98409841\begin{verbatim}9842>>> for pair in zip(s, t):9843... print(pair)9844...9845('a', 0)9846('b', 1)9847('c', 2)9848\end{verbatim}9849%9850A zip object is a kind of {\bf iterator}, which is any object9851that iterates through a sequence. Iterators are similar to lists in some9852ways, but unlike lists, you can't use an index to select an element from9853an iterator.9854\index{iterator}98559856If you want to use list operators and methods, you can9857use a zip object to make a list:98589859\begin{verbatim}9860>>> list(zip(s, t))9861[('a', 0), ('b', 1), ('c', 2)]9862\end{verbatim}9863%9864The result is a list of tuples; in this example, each tuple contains9865a character from the string and the corresponding element from9866the list.9867\index{list!of tuples}98689869If the sequences are not the same length, the result has the9870length of the shorter one.98719872\begin{verbatim}9873>>> list(zip('Anne', 'Elk'))9874[('A', 'E'), ('n', 'l'), ('n', 'k')]9875\end{verbatim}9876%9877You can use tuple assignment in a {\tt for} loop to traverse a list of9878tuples:9879\index{traversal}9880\index{tuple assignment}9881\index{assignment!tuple}98829883\begin{verbatim}9884t = [('a', 0), ('b', 1), ('c', 2)]9885for letter, number in t:9886print(number, letter)9887\end{verbatim}9888%9889Each time through the loop, Python selects the next tuple in9890the list and assigns the elements to {\tt letter} and9891{\tt number}. The output of this loop is:9892\index{loop}98939894\begin{verbatim}98950 a98961 b98972 c9898\end{verbatim}9899%9900If you combine {\tt zip}, {\tt for} and tuple assignment, you get a9901useful idiom for traversing two (or more) sequences at the same9902time. For example, \verb"has_match" takes two sequences, {\tt t1} and9903{\tt t2}, and returns {\tt True} if there is an index {\tt i}9904such that {\tt t1[i] == t2[i]}:9905\index{for loop}99069907\begin{verbatim}9908def has_match(t1, t2):9909for x, y in zip(t1, t2):9910if x == y:9911return True9912return False9913\end{verbatim}9914%9915If you need to traverse the elements of a sequence and their9916indices, you can use the built-in function {\tt enumerate}:9917\index{traversal}9918\index{enumerate function}9919\index{function!enumerate}99209921\begin{verbatim}9922for index, element in enumerate('abc'):9923print(index, element)9924\end{verbatim}9925%9926The result from {\tt enumerate} is an enumerate object, which9927iterates a sequence of pairs; each pair contains an index (starting9928from 0) and an element from the given sequence.9929In this example, the output is99309931\begin{verbatim}99320 a99331 b99342 c9935\end{verbatim}9936%9937Again.9938\index{iterator}9939\index{object!enumerate}9940\index{enumerate object}994199429943\section{Dictionaries and tuples}9944\label{dictuple}9945\index{dictionary}9946\index{items method}9947\index{method!items}9948\index{key-value pair}99499950Dictionaries have a method called {\tt items} that returns a sequence of9951tuples, where each tuple is a key-value pair.99529953\begin{verbatim}9954>>> d = {'a':0, 'b':1, 'c':2}9955>>> t = d.items()9956>>> t9957dict_items([('c', 2), ('a', 0), ('b', 1)])9958\end{verbatim}9959%9960The result is a \verb"dict_items" object, which is an iterator that9961iterates the key-value pairs. You can use it in a {\tt for} loop9962like this:9963\index{iterator}99649965\begin{verbatim}9966>>> for key, value in d.items():9967... print(key, value)9968...9969c 29970a 09971b 19972\end{verbatim}9973%9974As you should expect from a dictionary, the items are in no9975particular order.99769977Going in the other direction, you can use a list of tuples to9978initialize a new dictionary: \index{dictionary!initialize}99799980\begin{verbatim}9981>>> t = [('a', 0), ('c', 2), ('b', 1)]9982>>> d = dict(t)9983>>> d9984{'a': 0, 'c': 2, 'b': 1}9985\end{verbatim}99869987Combining {\tt dict} with {\tt zip} yields a concise way9988to create a dictionary:9989\index{zip function!use with dict}99909991\begin{verbatim}9992>>> d = dict(zip('abc', range(3)))9993>>> d9994{'a': 0, 'c': 2, 'b': 1}9995\end{verbatim}9996%9997The dictionary method {\tt update} also takes a list of tuples9998and adds them, as key-value pairs, to an existing dictionary.9999\index{update method}10000\index{method!update}10001\index{traverse!dictionary}10002\index{dictionary!traversal}1000310004It is common to use tuples as keys in dictionaries (primarily because10005you can't use lists). For example, a telephone directory might map10006from last-name, first-name pairs to telephone numbers. Assuming10007that we have defined {\tt last}, {\tt first} and {\tt number}, we10008could write:10009\index{tuple!as key in dictionary}10010\index{hashable}1001110012\begin{verbatim}10013directory[last, first] = number10014\end{verbatim}10015%10016The expression in brackets is a tuple. We could use tuple10017assignment to traverse this dictionary.10018\index{tuple!in brackets}1001910020\begin{verbatim}10021for last, first in directory:10022print(first, last, directory[last,first])10023\end{verbatim}10024%10025This loop traverses the keys in {\tt directory}, which are tuples. It10026assigns the elements of each tuple to {\tt last} and {\tt first}, then10027prints the name and corresponding telephone number.1002810029There are two ways to represent tuples in a state diagram. The more10030detailed version shows the indices and elements just as they appear in10031a list. For example, the tuple \verb"('Cleese', 'John')" would appear10032as in Figure~\ref{fig.tuple1}.10033\index{state diagram}10034\index{diagram!state}1003510036\begin{figure}10037\centerline10038{\includegraphics[scale=0.8]{figs/tuple1.pdf}}10039\caption{State diagram.}10040\label{fig.tuple1}10041\end{figure}1004210043But in a larger diagram you might want to leave out the10044details. For example, a diagram of the telephone directory might10045appear as in Figure~\ref{fig.dict2}.1004610047\begin{figure}10048\centerline10049{\includegraphics[scale=0.8]{figs/dict2.pdf}}10050\caption{State diagram.}10051\label{fig.dict2}10052\end{figure}1005310054Here the tuples are shown using Python syntax as a graphical10055shorthand. The telephone number in the diagram is the complaints line10056for the BBC, so please don't call it.100571005810059\section{Sequences of sequences}10060\index{sequence}1006110062I have focused on lists of tuples, but almost all of the examples in10063this chapter also work with lists of lists, tuples of tuples, and10064tuples of lists. To avoid enumerating the possible combinations, it10065is sometimes easier to talk about sequences of sequences.1006610067In many contexts, the different kinds of sequences (strings, lists and10068tuples) can be used interchangeably. So how should you choose one10069over the others?10070\index{string}10071\index{list}10072\index{tuple}10073\index{mutability}10074\index{immutability}1007510076To start with the obvious, strings are more limited than other10077sequences because the elements have to be characters. They are10078also immutable. If you need the ability to change the characters10079in a string (as opposed to creating a new string), you might10080want to use a list of characters instead.1008110082Lists are more common than tuples, mostly because they are mutable.10083But there are a few cases where you might prefer tuples:1008410085\begin{enumerate}1008610087\item In some contexts, like a {\tt return} statement, it is10088syntactically simpler to create a tuple than a list.1008910090\item If you want to use a sequence as a dictionary key, you10091have to use an immutable type like a tuple or string.1009210093\item If you are passing a sequence as an argument to a function,10094using tuples reduces the potential for unexpected behavior10095due to aliasing.1009610097\end{enumerate}1009810099Because tuples are immutable, they don't provide methods like {\tt10100sort} and {\tt reverse}, which modify existing lists. But Python10101provides the built-in function {\tt sorted}, which takes any sequence10102and returns a new list with the same elements in sorted order, and10103{\tt reversed}, which takes a sequence and returns an iterator that10104traverses the list in reverse order.10105\index{sorted function}10106\index{function!sorted} \index{reversed function}10107\index{function!reversed}10108\index{iterator}101091011010111\section{Debugging}10112\index{debugging}10113\index{data structure}10114\index{shape error}10115\index{error!shape}1011610117Lists, dictionaries and tuples are examples of {\bf data10118structures}; in this chapter we are starting to see compound data10119structures, like lists of tuples, or dictionaries that contain tuples10120as keys and lists as values. Compound data structures are useful, but10121they are prone to what I call {\bf shape errors}; that is, errors10122caused when a data structure has the wrong type, size, or structure.10123For example, if you are expecting a list with one integer and I10124give you a plain old integer (not in a list), it won't work.10125\index{structshape module}10126\index{module!structshape}1012710128To help debug these kinds of errors, I have written a module10129called {\tt structshape} that provides a function, also called10130{\tt structshape}, that takes any kind of data structure as10131an argument and returns a string that summarizes its shape.10132You can download it from \url{http://thinkpython2.com/code/structshape.py}1013310134Here's the result for a simple list:1013510136\begin{verbatim}10137>>> from structshape import structshape10138>>> t = [1, 2, 3]10139>>> structshape(t)10140'list of 3 int'10141\end{verbatim}10142%10143A fancier program might write ``list of 3 int{\em s}'', but it10144was easier not to deal with plurals. Here's a list of lists:1014510146\begin{verbatim}10147>>> t2 = [[1,2], [3,4], [5,6]]10148>>> structshape(t2)10149'list of 3 list of 2 int'10150\end{verbatim}10151%10152If the elements of the list are not the same type,10153{\tt structshape} groups them, in order, by type:1015410155\begin{verbatim}10156>>> t3 = [1, 2, 3, 4.0, '5', '6', [7], [8], 9]10157>>> structshape(t3)10158'list of (3 int, float, 2 str, 2 list of int, int)'10159\end{verbatim}10160%10161Here's a list of tuples:1016210163\begin{verbatim}10164>>> s = 'abc'10165>>> lt = list(zip(t, s))10166>>> structshape(lt)10167'list of 3 tuple of (int, str)'10168\end{verbatim}10169%10170And here's a dictionary with 3 items that map integers to strings.1017110172\begin{verbatim}10173>>> d = dict(lt)10174>>> structshape(d)10175'dict of 3 int->str'10176\end{verbatim}10177%10178If you are having trouble keeping track of your data structures,10179{\tt structshape} can help.101801018110182\section{Glossary}1018310184\begin{description}1018510186\item[tuple:] An immutable sequence of elements.10187\index{tuple}1018810189\item[tuple assignment:] An assignment with a sequence on the10190right side and a tuple of variables on the left. The right10191side is evaluated and then its elements are assigned to the10192variables on the left.10193\index{tuple assignment}10194\index{assignment!tuple}1019510196\item[gather:] An operation that collects multiple arguments into a tuple.10197\index{gather}1019810199\item[scatter:] An operation that makes a sequence behave like multiple arguments.10200\index{scatter}1020110202\item[zip object:] The result of calling a built-in function {\tt zip};10203an object that iterates through a sequence of tuples.10204\index{zip object}10205\index{object!zip}1020610207\item[iterator:] An object that can iterate through a sequence, but10208which does not provide list operators and methods.10209\index{iterator}1021010211\item[data structure:] A collection of related values, often10212organized in lists, dictionaries, tuples, etc.10213\index{data structure}1021410215\item[shape error:] An error caused because a value has the10216wrong shape; that is, the wrong type or size.10217\index{shape}1021810219\end{description}102201022110222\section{Exercises}1022310224\begin{exercise}1022510226Write a function called \verb"most_frequent" that takes a string and10227prints the letters in decreasing order of frequency. Find text10228samples from several different languages and see how letter frequency10229varies between languages. Compare your results with the tables at10230\url{http://en.wikipedia.org/wiki/Letter_frequencies}. Solution:10231\url{http://thinkpython2.com/code/most_frequent.py}. \index{letter10232frequency} \index{frequency!letter}1023310234\end{exercise}102351023610237\begin{exercise}10238\label{anagrams}10239\index{anagram set}10240\index{set!anagram}1024110242More anagrams!1024310244\begin{enumerate}1024510246\item Write a program10247that reads a word list from a file (see Section~\ref{wordlist}) and10248prints all the sets of words that are anagrams.1024910250Here is an example of what the output might look like:1025110252\begin{verbatim}10253['deltas', 'desalt', 'lasted', 'salted', 'slated', 'staled']10254['retainers', 'ternaries']10255['generating', 'greatening']10256['resmelts', 'smelters', 'termless']10257\end{verbatim}10258%10259Hint: you might want to build a dictionary that maps from a10260collection of letters to a list of words that can be spelled with those10261letters. The question is, how can you represent the collection of10262letters in a way that can be used as a key?1026310264\item Modify the previous program so that it prints the longest list10265of anagrams first, followed by the second longest, and so on.10266\index{Scrabble}10267\index{bingo}1026810269\item In Scrabble a ``bingo'' is when you play all seven tiles in10270your rack, along with a letter on the board, to form an eight-letter10271word. What collection of 8 letters forms the most possible bingos?1027210273% (7, ['angriest', 'astringe', 'ganister', 'gantries', 'granites',10274% 'ingrates', 'rangiest'])1027510276Solution: \url{http://thinkpython2.com/code/anagram_sets.py}.1027710278\end{enumerate}10279\end{exercise}1028010281\begin{exercise}10282\index{metathesis}1028310284Two words form a ``metathesis pair'' if you can transform one into the10285other by swapping two letters; for example, ``converse'' and10286``conserve''. Write a program that finds all of the metathesis pairs10287in the dictionary. Hint: don't test all pairs of words, and don't10288test all possible swaps. Solution:10289\url{http://thinkpython2.com/code/metathesis.py}. Credit: This10290exercise is inspired by an example at \url{http://puzzlers.org}.1029110292\end{exercise}102931029410295\begin{exercise}10296\index{Car Talk}10297\index{Puzzler}1029810299Here's another Car Talk Puzzler10300(\url{http://www.cartalk.com/content/puzzlers}):1030110302\begin{quote}10303What is the longest English word, that remains a valid English word,10304as you remove its letters one at a time?1030510306Now, letters can be removed from either end, or the middle, but you10307can't rearrange any of the letters. Every time you drop a letter, you10308wind up with another English word. If you do that, you're eventually10309going to wind up with one letter and that too is going to be an10310English word---one that's found in the dictionary. I want to know10311what's the longest word and how many letters does it10312have?1031310314I'm going to give you a little modest example: Sprite. Ok? You start10315off with sprite, you take a letter off, one from the interior of the10316word, take the r away, and we're left with the word spite, then we10317take the e off the end, we're left with spit, we take the s off, we're10318left with pit, it, and I.10319\end{quote}10320\index{reducible word}10321\index{word, reducible}1032210323Write a program to find all words that can be reduced in this way,10324and then find the longest one.1032510326This exercise is a little more challenging than most, so here are10327some suggestions:1032810329\begin{enumerate}1033010331\item You might want to write a function that takes a word and10332computes a list of all the words that can be formed by removing one10333letter. These are the ``children'' of the word.10334\index{recursive definition}10335\index{definition!recursive}1033610337\item Recursively, a word is reducible if any of its children10338are reducible. As a base case, you can consider the empty10339string reducible.1034010341\item The wordlist I provided, {\tt words.txt}, doesn't10342contain single letter words. So you might want to add10343``I'', ``a'', and the empty string.1034410345\item To improve the performance of your program, you might want10346to memoize the words that are known to be reducible.1034710348\end{enumerate}1034910350Solution: \url{http://thinkpython2.com/code/reducible.py}.1035110352\end{exercise}1035310354103551035610357%\begin{exercise}10358%\url{http://en.wikipedia.org/wiki/Word_Ladder}10359%\end{exercise}1036010361103621036310364\chapter{Case study: data structure selection}1036510366At this point you have learned about Python's core data structures,10367and you have seen some of the algorithms that use them.10368If you would like to know more about algorithms, this might be a good10369time to read Chapter~\ref{algorithms}.10370But you don't have to read it before you go on; you can read10371it whenever you are interested.1037210373This chapter presents a case study with exercises that let10374you think about choosing data structures and practice using them.103751037610377\section{Word frequency analysis}10378\label{analysis}1037910380As usual, you should at least attempt the exercises10381before you read my solutions.1038210383\begin{exercise}1038410385Write a program that reads a file, breaks each line into10386words, strips whitespace and punctuation from the words, and10387converts them to lowercase.10388\index{string module}10389\index{module!string}1039010391Hint: The {\tt string} module provides a string named {\tt whitespace},10392which contains space, tab, newline, etc., and {\tt10393punctuation} which contains the punctuation characters. Let's see10394if we can make Python swear:1039510396\begin{verbatim}10397>>> import string10398>>> string.punctuation10399'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'10400\end{verbatim}10401%10402Also, you might consider using the string methods {\tt strip},10403{\tt replace} and {\tt translate}.10404\index{strip method}10405\index{method!strip}10406\index{replace method}10407\index{method!replace}10408\index{translate method}10409\index{method!translate}1041010411\end{exercise}104121041310414\begin{exercise}10415\index{Project Gutenberg}1041610417Go to Project Gutenberg (\url{http://gutenberg.org}) and download10418your favorite out-of-copyright book in plain text format.10419\index{plain text}10420\index{text!plain}1042110422Modify your program from the previous exercise to read the book10423you downloaded, skip over the header information at the beginning10424of the file, and process the rest of the words as before.1042510426Then modify the program to count the total number of words in10427the book, and the number of times each word is used.10428\index{word frequency}10429\index{frequency!word}1043010431Print the number of different words used in the book. Compare10432different books by different authors, written in different eras.10433Which author uses the most extensive vocabulary?10434\end{exercise}104351043610437\begin{exercise}1043810439Modify the program from the previous exercise to print the1044020 most frequently used words in the book.1044110442\end{exercise}104431044410445\begin{exercise}1044610447Modify the previous program to read a word list (see10448Section~\ref{wordlist}) and then print all the words in the book that10449are not in the word list. How many of them are typos? How many of10450them are common words that {\em should} be in the word list, and how10451many of them are really obscure?1045210453\end{exercise}104541045510456\section{Random numbers}10457\index{random number}10458\index{number, random}10459\index{deterministic}10460\index{pseudorandom}1046110462Given the same inputs, most computer programs generate the same10463outputs every time, so they are said to be {\bf deterministic}.10464Determinism is usually a good thing, since we expect the same10465calculation to yield the same result. For some applications, though,10466we want the computer to be unpredictable. Games are an obvious10467example, but there are more.1046810469Making a program truly nondeterministic turns out to be difficult,10470but there are ways to make it at least seem nondeterministic. One of10471them is to use algorithms that generate {\bf pseudorandom} numbers.10472Pseudorandom numbers are not truly random because they are generated10473by a deterministic computation, but just by looking at the numbers it10474is all but impossible to distinguish them from random.10475\index{random module}10476\index{module!random}1047710478The {\tt random} module provides functions that generate10479pseudorandom numbers (which I will simply call ``random'' from10480here on).10481\index{random function}10482\index{function!random}1048310484The function {\tt random} returns a random float10485between 0.0 and 1.0 (including 0.0 but not 1.0). Each time you10486call {\tt random}, you get the next number in a long series. To see a10487sample, run this loop:1048810489\begin{verbatim}10490import random1049110492for i in range(10):10493x = random.random()10494print(x)10495\end{verbatim}10496%10497The function {\tt randint} takes parameters {\tt low} and10498{\tt high} and returns an integer between {\tt low} and10499{\tt high} (including both).10500\index{randint function}10501\index{function!randint}1050210503\begin{verbatim}10504>>> random.randint(5, 10)10505510506>>> random.randint(5, 10)10507910508\end{verbatim}10509%10510To choose an element from a sequence at random, you can use10511{\tt choice}:10512\index{choice function}10513\index{function!choice}1051410515\begin{verbatim}10516>>> t = [1, 2, 3]10517>>> random.choice(t)10518210519>>> random.choice(t)10520310521\end{verbatim}10522%10523The {\tt random} module also provides functions to generate10524random values from continuous distributions including10525Gaussian, exponential, gamma, and a few more.1052610527\begin{exercise}10528\index{histogram!random choice}1052910530Write a function named \verb"choose_from_hist" that takes10531a histogram as defined in Section~\ref{histogram} and returns a10532random value from the histogram, chosen with probability10533in proportion to frequency. For example, for this histogram:1053410535\begin{verbatim}10536>>> t = ['a', 'a', 'b']10537>>> hist = histogram(t)10538>>> hist10539{'a': 2, 'b': 1}10540\end{verbatim}10541%10542your function should return \verb"'a'" with probability $2/3$ and \verb"'b'"10543with probability $1/3$.10544\end{exercise}105451054610547\section{Word histogram}1054810549You should attempt the previous exercises before you go on.10550You can download my solution from10551\url{http://thinkpython2.com/code/analyze_book1.py}. You will10552also need \url{http://thinkpython2.com/code/emma.txt}.1055310554Here is a program that reads a file and builds a histogram of the10555words in the file:10556\index{histogram!word frequencies}1055710558\begin{verbatim}10559import string1056010561def process_file(filename):10562hist = dict()10563fp = open(filename)10564for line in fp:10565process_line(line, hist)10566return hist1056710568def process_line(line, hist):10569line = line.replace('-', ' ')1057010571for word in line.split():10572word = word.strip(string.punctuation + string.whitespace)10573word = word.lower()10574hist[word] = hist.get(word, 0) + 11057510576hist = process_file('emma.txt')10577\end{verbatim}10578%10579This program reads {\tt emma.txt}, which contains the text of {\em10580Emma} by Jane Austen.10581\index{Austin, Jane}1058210583\verb"process_file" loops through the lines of the file,10584passing them one at a time to \verb"process_line". The histogram10585{\tt hist} is being used as an accumulator.10586\index{accumulator!histogram}10587\index{traversal}1058810589\verb"process_line" uses the string method {\tt replace} to replace10590hyphens with spaces before using {\tt split} to break the line into a10591list of strings. It traverses the list of words and uses {\tt strip}10592and {\tt lower} to remove punctuation and convert to lower case. (It10593is a shorthand to say that strings are ``converted''; remember that10594strings are immutable, so methods like {\tt strip} and {\tt lower}10595return new strings.)1059610597Finally, \verb"process_line" updates the histogram by creating a new10598item or incrementing an existing one.10599\index{update!histogram}1060010601To count the total number of words in the file, we can add up10602the frequencies in the histogram:1060310604\begin{verbatim}10605def total_words(hist):10606return sum(hist.values())10607\end{verbatim}10608%10609The number of different words is just the number of items in10610the dictionary:1061110612\begin{verbatim}10613def different_words(hist):10614return len(hist)10615\end{verbatim}10616%10617Here is some code to print the results:1061810619\begin{verbatim}10620print('Total number of words:', total_words(hist))10621print('Number of different words:', different_words(hist))10622\end{verbatim}10623%10624And the results:1062510626\begin{verbatim}10627Total number of words: 16108010628Number of different words: 721410629\end{verbatim}10630%1063110632\section{Most common words}1063310634To find the most common words, we can make a list of tuples,10635where each tuple contains a word and its frequency,10636and sort it.1063710638The following function takes a histogram and returns a list of10639word-frequency tuples:1064010641\begin{verbatim}10642def most_common(hist):10643t = []10644for key, value in hist.items():10645t.append((value, key))1064610647t.sort(reverse=True)10648return t10649\end{verbatim}1065010651In each tuple, the frequency appears first, so the resulting list is10652sorted by frequency. Here is a loop that prints the ten most common10653words:1065410655\begin{verbatim}10656t = most_common(hist)10657print('The most common words are:')10658for freq, word in t[:10]:10659print(word, freq, sep='\t')10660\end{verbatim}10661%10662I use the keyword argument {\tt sep} to tell {\tt print} to use a tab10663character as a ``separator'', rather than a space, so the second10664column is lined up. Here are the results from {\em Emma}:1066510666\begin{verbatim}10667The most common words are:10668to 524210669the 520510670and 489710671of 429510672i 319110673a 313010674it 252910675her 248310676was 240010677she 236410678\end{verbatim}10679%10680This code can be simplified using the {\tt key} parameter of10681the {\tt sort} function. If you are curious, you can read about it10682at \url{https://wiki.python.org/moin/HowTo/Sorting}.106831068410685\section{Optional parameters}10686\index{optional parameter}10687\index{parameter!optional}1068810689We have seen built-in functions and methods that take optional10690arguments. It is possible to write programmer-defined functions10691with optional arguments, too. For example, here is a function that10692prints the most common words in a histogram10693\index{programmer-defined function}10694\index{function!programmer defined}1069510696\begin{verbatim}10697def print_most_common(hist, num=10):10698t = most_common(hist)10699print('The most common words are:')10700for freq, word in t[:num]:10701print(word, freq, sep='\t')10702\end{verbatim}1070310704The first parameter is required; the second is optional.10705The {\bf default value} of {\tt num} is 10.10706\index{default value}10707\index{value!default}1070810709If you only provide one argument:1071010711\begin{verbatim}10712print_most_common(hist)10713\end{verbatim}1071410715{\tt num} gets the default value. If you provide two arguments:1071610717\begin{verbatim}10718print_most_common(hist, 20)10719\end{verbatim}1072010721{\tt num} gets the value of the argument instead. In other10722words, the optional argument {\bf overrides} the default value.10723\index{override}1072410725If a function has both required and optional parameters, all10726the required parameters have to come first, followed by the10727optional ones.107281072910730\section{Dictionary subtraction}10731\label{dictsub}10732\index{dictionary!subtraction}10733\index{subtraction!dictionary}1073410735Finding the words from the book that are not in the word list10736from {\tt words.txt} is a problem you might recognize as set10737subtraction; that is, we want to find all the words from one10738set (the words in the book) that are not in the other (the10739words in the list).1074010741{\tt subtract} takes dictionaries {\tt d1} and {\tt d2} and returns a10742new dictionary that contains all the keys from {\tt d1} that are not10743in {\tt d2}. Since we don't really care about the values, we10744set them all to None.1074510746\begin{verbatim}10747def subtract(d1, d2):10748res = dict()10749for key in d1:10750if key not in d2:10751res[key] = None10752return res10753\end{verbatim}10754%10755To find the words in the book that are not in {\tt words.txt},10756we can use \verb"process_file" to build a histogram for10757{\tt words.txt}, and then subtract:1075810759\begin{verbatim}10760words = process_file('words.txt')10761diff = subtract(hist, words)1076210763print("Words in the book that aren't in the word list:")10764for word in diff:10765print(word, end=' ')10766\end{verbatim}10767%10768Here are some of the results from {\em Emma}:1076910770\begin{verbatim}10771Words in the book that aren't in the word list:10772rencontre jane's blanche woodhouses disingenuousness10773friend's venice apartment ...10774\end{verbatim}10775%10776Some of these words are names and possessives. Others, like10777``rencontre'', are no longer in common use. But a few are common10778words that should really be in the list!1077910780\begin{exercise}10781\index{set}10782\index{type!set}1078310784Python provides a data structure called {\tt set} that provides many10785common set operations. You can read about them in Section~\ref{sets},10786or read the documentation at10787\url{http://docs.python.org/3/library/stdtypes.html#types-set}.1078810789Write a program that uses set subtraction to find words in the book10790that are not in the word list. Solution:10791\url{http://thinkpython2.com/code/analyze_book2.py}.1079210793\end{exercise}107941079510796\section{Random words}10797\label{randomwords}10798\index{histogram!random choice}1079910800To choose a random word from the histogram, the simplest algorithm10801is to build a list with multiple copies of each word, according10802to the observed frequency, and then choose from the list:1080310804\begin{verbatim}10805def random_word(h):10806t = []10807for word, freq in h.items():10808t.extend([word] * freq)1080910810return random.choice(t)10811\end{verbatim}10812%10813The expression {\tt [word] * freq} creates a list with {\tt freq}10814copies of the string {\tt word}. The {\tt extend}10815method is similar to {\tt append} except that the argument is10816a sequence.1081710818This algorithm works, but it is not very efficient; each time you10819choose a random word, it rebuilds the list, which is as big as10820the original book. An obvious improvement is to build the list10821once and then make multiple selections, but the list is still big.1082210823An alternative is:1082410825\begin{enumerate}1082610827\item Use {\tt keys} to get a list of the words in the book.1082810829\item Build a list that contains the cumulative sum of the word10830frequencies (see Exercise~\ref{cumulative}). The last item10831in this list is the total number of words in the book, $n$.1083210833\item Choose a random number from 1 to $n$. Use a bisection search10834(See Exercise~\ref{bisection}) to find the index where the random10835number would be inserted in the cumulative sum.1083610837\item Use the index to find the corresponding word in the word list.1083810839\end{enumerate}1084010841\begin{exercise}10842\label{randhist}10843\index{algorithm}1084410845Write a program that uses this algorithm to choose a random word from10846the book. Solution:10847\url{http://thinkpython2.com/code/analyze_book3.py}.1084810849\end{exercise}10850108511085210853\section{Markov analysis}10854\label{markov}10855\index{Markov analysis}1085610857If you choose words from the book at random, you can get a10858sense of the vocabulary, but you probably won't get a sentence:1085910860\begin{verbatim}10861this the small regard harriet which knightley's it most things10862\end{verbatim}10863%10864A series of random words seldom makes sense because there10865is no relationship between successive words. For example, in10866a real sentence you would expect an article like ``the'' to10867be followed by an adjective or a noun, and probably not a verb10868or adverb.1086910870One way to measure these kinds of relationships is Markov10871analysis, which10872characterizes, for a given sequence of words, the probability of the10873words that might come next. For example, the song {\em Eric, the Half a10874Bee} begins:1087510876\begin{quote}10877Half a bee, philosophically, \\10878Must, ipso facto, half not be. \\10879But half the bee has got to be \\10880Vis a vis, its entity. D'you see? \\10881\\10882But can a bee be said to be \\10883Or not to be an entire bee \\10884When half the bee is not a bee \\10885Due to some ancient injury? \\10886\end{quote}10887%10888In this text,10889the phrase ``half the'' is always followed by the word ``bee'',10890but the phrase ``the bee'' might be followed by either10891``has'' or ``is''.10892\index{prefix}10893\index{suffix}10894\index{mapping}1089510896The result of Markov analysis is a mapping from each prefix10897(like ``half the'' and ``the bee'') to all possible suffixes10898(like ``has'' and ``is'').10899\index{random text}10900\index{text!random}1090110902Given this mapping, you can generate a random text by10903starting with any prefix and choosing at random from the10904possible suffixes. Next, you can combine the end of the10905prefix and the new suffix to form the next prefix, and repeat.1090610907For example, if you start with the prefix ``Half a'', then the10908next word has to be ``bee'', because the prefix only appears10909once in the text. The next prefix is ``a bee'', so the10910next suffix might be ``philosophically'', ``be'' or ``due''.1091110912In this example the length of the prefix is always two, but10913you can do Markov analysis with any prefix length.1091410915\begin{exercise}1091610917Markov analysis:1091810919\begin{enumerate}1092010921\item Write a program to read a text from a file and perform Markov10922analysis. The result should be a dictionary that maps from10923prefixes to a collection of possible suffixes. The collection10924might be a list, tuple, or dictionary; it is up to you to make10925an appropriate choice. You can test your program with prefix10926length two, but you should write the program in a way that makes10927it easy to try other lengths.1092810929\item Add a function to the previous program to generate random text10930based on the Markov analysis. Here is an example from {\em Emma}10931with prefix length 2:1093210933\begin{quote}10934He was very clever, be it sweetness or be angry, ashamed or only10935amused, at such a stroke. She had never thought of Hannah till you10936were never meant for me?" "I cannot make speeches, Emma:" he soon cut10937it all himself.10938\end{quote}1093910940For this example, I left the punctuation attached to the words.10941The result is almost syntactically correct, but not quite.10942Semantically, it almost makes sense, but not quite.1094310944What happens if you increase the prefix length? Does the random10945text make more sense?1094610947\item Once your program is working, you might want to try a mash-up:10948if you combine text from two or more books, the random10949text you generate will blend the vocabulary and phrases from10950the sources in interesting ways.10951\index{mash-up}1095210953\end{enumerate}1095410955Credit: This case study is based on an example from Kernighan and10956Pike, {\em The Practice of Programming}, Addison-Wesley, 1999.1095710958\end{exercise}1095910960You should attempt this exercise before you go on; then you can10961download my solution from \url{http://thinkpython2.com/code/markov.py}.10962You will also need \url{http://thinkpython2.com/code/emma.txt}.109631096410965\section{Data structures}10966\index{data structure}1096710968Using Markov analysis to generate random text is fun, but there is10969also a point to this exercise: data structure selection. In your10970solution to the previous exercises, you had to choose:1097110972\begin{itemize}1097310974\item How to represent the prefixes.1097510976\item How to represent the collection of possible suffixes.1097710978\item How to represent the mapping from each prefix to10979the collection of possible suffixes.1098010981\end{itemize}1098210983The last one is easy: a dictionary is the obvious choice10984for a mapping from keys to corresponding values.1098510986For the prefixes, the most obvious options are string,10987list of strings, or tuple of strings.1098810989For the suffixes,10990one option is a list; another is a histogram (dictionary).10991\index{implementation}1099210993How should you choose? The first step is to think about10994the operations you will need to implement for each data structure.10995For the prefixes, we need to be able to remove words from10996the beginning and add to the end. For example, if the current10997prefix is ``Half a'', and the next word is ``bee'', you need10998to be able to form the next prefix, ``a bee''.10999\index{tuple!as key in dictionary}1100011001Your first choice might be a list, since it is easy to add11002and remove elements, but we also need to be able to use the11003prefixes as keys in a dictionary, so that rules out lists.11004With tuples, you can't append or remove, but you can use11005the addition operator to form a new tuple:1100611007\begin{verbatim}11008def shift(prefix, word):11009return prefix[1:] + (word,)11010\end{verbatim}11011%11012{\tt shift} takes a tuple of words, {\tt prefix}, and a string,11013{\tt word}, and forms a new tuple that has all the words11014in {\tt prefix} except the first, and {\tt word} added to11015the end.1101611017For the collection of suffixes, the operations we need to11018perform include adding a new suffix (or increasing the frequency11019of an existing one), and choosing a random suffix.1102011021Adding a new suffix is equally easy for the list implementation11022or the histogram. Choosing a random element from a list11023is easy; choosing from a histogram is harder to do11024efficiently (see Exercise~\ref{randhist}).1102511026So far we have been talking mostly about ease of implementation,11027but there are other factors to consider in choosing data structures.11028One is run time. Sometimes there is a theoretical reason to expect11029one data structure to be faster than other; for example, I mentioned11030that the {\tt in} operator is faster for dictionaries than for lists,11031at least when the number of elements is large.1103211033But often you don't know ahead of time which implementation will11034be faster. One option is to implement both of them and see which11035is better. This approach is called {\bf benchmarking}. A practical11036alternative is to choose the data structure that is11037easiest to implement, and then see if it is fast enough for the11038intended application. If so, there is no need to go on. If not,11039there are tools, like the {\tt profile} module, that can identify11040the places in a program that take the most time.11041\index{benchmarking}11042\index{profile module}11043\index{module!profile}1104411045The other factor to consider is storage space. For example, using a11046histogram for the collection of suffixes might take less space because11047you only have to store each word once, no matter how many times it11048appears in the text. In some cases, saving space can also make your11049program run faster, and in the extreme, your program might not run at11050all if you run out of memory. But for many applications, space is a11051secondary consideration after run time.1105211053One final thought: in this discussion, I have implied that11054we should use one data structure for both analysis and generation. But11055since these are separate phases, it would also be possible to use one11056structure for analysis and then convert to another structure for11057generation. This would be a net win if the time saved during11058generation exceeded the time spent in conversion.110591106011061\section{Debugging}11062\index{debugging}1106311064When you are debugging a program, and especially if you are11065working on a hard bug, there are five things to try:1106611067\begin{description}1106811069\item[Reading:] Examine your code, read it back to yourself, and11070check that it says what you meant to say.1107111072\item[Running:] Experiment by making changes and running different11073versions. Often if you display the right thing at the right place11074in the program, the problem becomes obvious, but sometimes you have to11075build scaffolding.1107611077\item[Ruminating:] Take some time to think! What kind of error11078is it: syntax, runtime, or semantic? What information can you get from11079the error messages, or from the output of the program? What kind of11080error could cause the problem you're seeing? What did you change11081last, before the problem appeared?1108211083\item[Rubberducking:] If you explain the problem to someone else, you11084sometimes find the answer before you finish asking the question.11085Often you don't need the other person; you could just talk to a rubber11086duck. And that's the origin of the well-known strategy called {\bf11087rubber duck debugging}. I am not making this up; see11088\url{https://en.wikipedia.org/wiki/Rubber_duck_debugging}.1108911090\item[Retreating:] At some point, the best thing to do is back11091off, undoing recent changes, until you get back to a program that11092works and that you understand. Then you can start rebuilding.1109311094\end{description}1109511096Beginning programmers sometimes get stuck on one of these activities11097and forget the others. Each activity comes with its own failure11098mode.11099\index{typographical error}1110011101For example, reading your code might help if the problem is a11102typographical error, but not if the problem is a conceptual11103misunderstanding. If you don't understand what your program does, you11104can read it 100 times and never see the error, because the error is in11105your head.11106\index{experimental debugging}1110711108Running experiments can help, especially if you run small, simple11109tests. But if you run experiments without thinking or reading your11110code, you might fall into a pattern I call ``random walk programming'',11111which is the process of making random changes until the program11112does the right thing. Needless to say, random walk programming11113can take a long time.11114\index{random walk programming}11115\index{development plan!random walk programming}1111611117You have to take time to think. Debugging is like an11118experimental science. You should have at least one hypothesis about11119what the problem is. If there are two or more possibilities, try to11120think of a test that would eliminate one of them.1112111122But even the best debugging techniques will fail if there are too many11123errors, or if the code you are trying to fix is too big and11124complicated. Sometimes the best option is to retreat, simplifying the11125program until you get to something that works and that you11126understand.1112711128Beginning programmers are often reluctant to retreat because11129they can't stand to delete a line of code (even if it's wrong).11130If it makes you feel better, copy your program into another file11131before you start stripping it down. Then you can copy the pieces11132back one at a time.1113311134Finding a hard bug requires reading, running, ruminating, and11135sometimes retreating. If you get stuck on one of these activities,11136try the others.111371113811139\section{Glossary}1114011141\begin{description}1114211143\item[deterministic:] Pertaining to a program that does the same11144thing each time it runs, given the same inputs.11145\index{deterministic}1114611147\item[pseudorandom:] Pertaining to a sequence of numbers that appears11148to be random, but is generated by a deterministic program.11149\index{pseudorandom}1115011151\item[default value:] The value given to an optional parameter if no11152argument is provided.11153\index{default value}1115411155\item[override:] To replace a default value with an argument.11156\index{override}1115711158\item[benchmarking:] The process of choosing between data structures11159by implementing alternatives and testing them on a sample of the11160possible inputs.11161\index{benchmarking}1116211163\item[rubber duck debugging:] Debugging by explaining your problem11164to an inanimate object such as a rubber duck. Articulating the11165problem can help you solve it, even if the rubber duck doesn't know11166Python.11167\index{rubber duck debugging}11168\index{debugging!rubber duck}1116911170\end{description}111711117211173\section{Exercises}1117411175\begin{exercise}11176\index{word frequency}11177\index{frequency!word}11178\index{Zipf's law}1117911180The ``rank'' of a word is its position in a list of words11181sorted by frequency: the most common word has rank 1, the11182second most common has rank 2, etc.1118311184Zipf's law describes a relationship between the ranks and frequencies11185of words in natural languages11186(\url{http://en.wikipedia.org/wiki/Zipf's_law}). Specifically, it11187predicts that the frequency, $f$, of the word with rank $r$ is:1118811189\[ f = c r^{-s} \]11190%11191where $s$ and $c$ are parameters that depend on the language and the11192text. If you take the logarithm of both sides of this equation, you11193get:11194\index{logarithm}1119511196\[ \log f = \log c - s \log r \]11197%11198So if you plot log $f$ versus log $r$, you should get11199a straight line with slope $-s$ and intercept log $c$.1120011201Write a program that reads a text from a file, counts11202word frequencies, and prints one line11203for each word, in descending order of frequency, with11204log $f$ and log $r$. Use the graphing program of your11205choice to plot the results and check whether they form11206a straight line. Can you estimate the value of $s$?1120711208Solution: \url{http://thinkpython2.com/code/zipf.py}.11209To run my solution, you need the plotting module {\tt matplotlib}.11210If you installed Anaconda, you already have {\tt matplotlib};11211otherwise you might have to install it.11212\index{matplotlib}1121311214\end{exercise}11215112161121711218\chapter{Files}1121911220This chapter introduces the idea of ``persistent'' programs that11221keep data in permanent storage, and shows how to use different11222kinds of permanent storage, like files and databases.112231122411225\section{Persistence}11226\index{file}11227\index{type!file}11228\index{persistence}1122911230Most of the programs we have seen so far are transient in the11231sense that they run for a short time and produce some output,11232but when they end, their data disappears. If you run the program11233again, it starts with a clean slate.1123411235Other programs are {\bf persistent}: they run for a long time11236(or all the time); they keep at least some of their data11237in permanent storage (a hard drive, for example); and11238if they shut down and restart, they pick up where they left off.1123911240Examples of persistent programs are operating systems, which11241run pretty much whenever a computer is on, and web servers,11242which run all the time, waiting for requests to come in on11243the network.1124411245One of the simplest ways for programs to maintain their data11246is by reading and writing text files. We have already seen11247programs that read text files; in this chapter we will see programs11248that write them.1124911250An alternative is to store the state of the program in a database.11251In this chapter I will present a simple database and a module,11252{\tt pickle}, that makes it easy to store program data.11253\index{pickle module}11254\index{module!pickle}112551125611257\section{Reading and writing}11258\index{file!reading and writing}1125911260A text file is a sequence of characters stored on a permanent11261medium like a hard drive, flash memory, or CD-ROM. We saw how11262to open and read a file in Section~\ref{wordlist}.11263\index{open function}11264\index{function!open}1126511266To write a file, you have to open it with mode \verb"'w'" as a second11267parameter:1126811269\begin{verbatim}11270>>> fout = open('output.txt', 'w')11271\end{verbatim}11272%11273If the file already exists, opening it in write mode clears out11274the old data and starts fresh, so be careful!11275If the file doesn't exist, a new one is created.1127611277{\tt open} returns a file object that provides methods for working11278with the file.11279The {\tt write} method puts data into the file.1128011281\begin{verbatim}11282>>> line1 = "This here's the wattle,\n"11283>>> fout.write(line1)112842411285\end{verbatim}11286%11287The return value is the number of characters that were written.11288The file object keeps track of where it is, so if11289you call {\tt write} again, it adds the new data to the end of11290the file.1129111292\begin{verbatim}11293>>> line2 = "the emblem of our land.\n"11294>>> fout.write(line2)112952411296\end{verbatim}11297%11298When you are done writing, you should close the file.1129911300\begin{verbatim}11301>>> fout.close()11302\end{verbatim}11303%11304\index{close method}11305\index{method!close}11306%11307If you don't close the file, it gets closed for you when the11308program ends.113091131011311\section{Format operator}11312\index{format operator}11313\index{operator!format}1131411315The argument of {\tt write} has to be a string, so if we want11316to put other values in a file, we have to convert them to11317strings. The easiest way to do that is with {\tt str}:1131811319\begin{verbatim}11320>>> x = 5211321>>> fout.write(str(x))11322\end{verbatim}11323%11324An alternative is to use the {\bf format operator}, {\tt \%}. When11325applied to integers, {\tt \%} is the modulus operator. But11326when the first operand is a string, {\tt \%} is the format operator.11327\index{format string}1132811329The first operand is the {\bf format string}, which contains11330one or more {\bf format sequences}, which11331specify how11332the second operand is formatted. The result is a string.11333\index{format sequence}1133411335For example, the format sequence \verb"'%d'" means that11336the second operand should be formatted as a decimal11337integer:1133811339\begin{verbatim}11340>>> camels = 4211341>>> '%d' % camels11342'42'11343\end{verbatim}11344%11345The result is the string \verb"'42'", which is not to be confused11346with the integer value {\tt 42}.1134711348A format sequence can appear anywhere in the string,11349so you can embed a value in a sentence:1135011351\begin{verbatim}11352>>> 'I have spotted %d camels.' % camels11353'I have spotted 42 camels.'11354\end{verbatim}11355%11356If there is more than one format sequence in the string,11357the second argument has to be a tuple. Each format sequence is11358matched with an element of the tuple, in order.1135911360The following example uses \verb"'%d'" to format an integer,11361\verb"'%g'" to format a floating-point number, and11362\verb"'%s'" to format a string:1136311364\begin{verbatim}11365>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')11366'In 3 years I have spotted 0.1 camels.'11367\end{verbatim}11368%11369The number of elements in the tuple has to match the number11370of format sequences in the string. Also, the types of the11371elements have to match the format sequences:11372\index{exception!TypeError}11373\index{TypeError}1137411375\begin{verbatim}11376>>> '%d %d %d' % (1, 2)11377TypeError: not enough arguments for format string11378>>> '%d' % 'dollars'11379TypeError: %d format: a number is required, not str11380\end{verbatim}11381%11382In the first example, there aren't enough elements; in the11383second, the element is the wrong type.1138411385For more information on the format operator, see11386\url{https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting}. A more powerful alternative is the string11387format method, which you can read about at11388\url{https://docs.python.org/3/library/stdtypes.html#str.format}.1138911390% You can specify the number of digits as part of the format sequence.11391% For example, the sequence \verb"'%8.2f'"11392% formats a floating-point number to be 8 characters long, with11393% 2 digits after the decimal point:1139411395% % \begin{verbatim}11396% >>> '%8.2f' % 3.1415911397% ' 3.14'11398% \end{verbatim}11399% \afterverb11400% %11401% The result takes up eight spaces with two11402% digits after the decimal point.114031140411405\section{Filenames and paths}11406\label{paths}11407\index{filename}11408\index{path}11409\index{directory}11410\index{folder}1141111412Files are organized into {\bf directories} (also called ``folders'').11413Every running program has a ``current directory'', which is the11414default directory for most operations.11415For example, when you open a file for reading, Python looks for it in the11416current directory.11417\index{os module}11418\index{module!os}1141911420The {\tt os} module provides functions for working with files and11421directories (``os'' stands for ``operating system''). {\tt os.getcwd}11422returns the name of the current directory:11423\index{getcwd function}11424\index{function!getcwd}1142511426\begin{verbatim}11427>>> import os11428>>> cwd = os.getcwd()11429>>> cwd11430'/home/dinsdale'11431\end{verbatim}11432%11433{\tt cwd} stands for ``current working directory''. The result in11434this example is {\tt /home/dinsdale}, which is the home directory of a11435user named {\tt dinsdale}.11436\index{working directory}11437\index{directory!working}1143811439A string like \verb"'/home/dinsdale'" that identifies a file or11440directory is called a {\bf path}.1144111442A simple filename, like {\tt memo.txt} is also considered a path,11443but it is a {\bf relative path} because it relates to the current11444directory. If the current directory is {\tt /home/dinsdale}, the11445filename {\tt memo.txt} would refer to {\tt /home/dinsdale/memo.txt}.11446\index{relative path} \index{path!relative}11447\index{absolute path} \index{path!absolute}1144811449A path that begins with {\tt /} does not depend on the current11450directory; it is called an {\bf absolute path}. To find the absolute11451path to a file, you can use {\tt os.path.abspath}:1145211453\begin{verbatim}11454>>> os.path.abspath('memo.txt')11455'/home/dinsdale/memo.txt'11456\end{verbatim}11457%11458{\tt os.path} provides other functions for working with filenames11459and paths. For example,11460{\tt os.path.exists} checks11461whether a file or directory exists:11462\index{exists function}11463\index{function!exists}1146411465\begin{verbatim}11466>>> os.path.exists('memo.txt')11467True11468\end{verbatim}11469%11470If it exists, {\tt os.path.isdir} checks whether it's a directory:1147111472\begin{verbatim}11473>>> os.path.isdir('memo.txt')11474False11475>>> os.path.isdir('/home/dinsdale')11476True11477\end{verbatim}11478%11479Similarly, {\tt os.path.isfile} checks whether it's a file.1148011481{\tt os.listdir} returns a list of the files (and other directories)11482in the given directory:1148311484\begin{verbatim}11485>>> os.listdir(cwd)11486['music', 'photos', 'memo.txt']11487\end{verbatim}11488%11489To demonstrate these functions, the following example11490``walks'' through a directory, prints11491the names of all the files, and calls itself recursively on11492all the directories.11493\index{walk, directory}11494\index{directory!walk}1149511496\begin{verbatim}11497def walk(dirname):11498for name in os.listdir(dirname):11499path = os.path.join(dirname, name)1150011501if os.path.isfile(path):11502print(path)11503else:11504walk(path)11505\end{verbatim}11506%11507{\tt os.path.join} takes a directory and a file name and joins11508them into a complete path.1150911510The {\tt os} module provides a function called {\tt walk} that is11511similar to this one but more versatile. As an exercise, read the11512documentation and use it to print the names of the files in a given11513directory and its subdirectories. You can download my solution from11514\url{http://thinkpython2.com/code/walk.py}.115151151611517\section{Catching exceptions}11518\label{catch}1151911520A lot of things can go wrong when you try to read and write11521files. If you try to open a file that doesn't exist, you get an11522{\tt IOError}:11523\index{open function}11524\index{function!open}11525\index{exception!IOError}11526\index{IOError}1152711528\begin{verbatim}11529>>> fin = open('bad_file')11530IOError: [Errno 2] No such file or directory: 'bad_file'11531\end{verbatim}11532%11533If you don't have permission to access a file:11534\index{file!permission}11535\index{permission, file}1153611537\begin{verbatim}11538>>> fout = open('/etc/passwd', 'w')11539PermissionError: [Errno 13] Permission denied: '/etc/passwd'11540\end{verbatim}11541%11542And if you try to open a directory for reading, you get1154311544\begin{verbatim}11545>>> fin = open('/home')11546IsADirectoryError: [Errno 21] Is a directory: '/home'11547\end{verbatim}11548%11549To avoid these errors, you could use functions like {\tt os.path.exists}11550and {\tt os.path.isfile}, but it would take a lot of time and code11551to check all the possibilities (if ``{\tt Errno 21}'' is any11552indication, there are at least 21 things that can go wrong).11553\index{exception, catching}11554\index{try statement}11555\index{statement!try}1155611557It is better to go ahead and try---and deal with problems if they11558happen---which is exactly what the {\tt try} statement does. The11559syntax is similar to an {\tt if...else} statement:1156011561\begin{verbatim}11562try:11563fin = open('bad_file')11564except:11565print('Something went wrong.')11566\end{verbatim}11567%11568Python starts by executing the {\tt try} clause. If all goes11569well, it skips the {\tt except} clause and proceeds. If an11570exception occurs, it jumps out of the {\tt try} clause and11571runs the {\tt except} clause.1157211573Handling an exception with a {\tt try} statement is called {\bf11574catching} an exception. In this example, the {\tt except} clause11575prints an error message that is not very helpful. In general,11576catching an exception gives you a chance to fix the problem, or try11577again, or at least end the program gracefully.115781157911580\section{Databases}11581\index{database}1158211583A {\bf database} is a file that is organized for storing data. Many11584databases are organized like a dictionary in the sense that they map11585from keys to values. The biggest difference between a database and a11586dictionary is that the database is on disk (or other permanent11587storage), so it persists after the program ends. \index{dbm11588module} \index{module!dbm}1158911590The module {\tt dbm} provides an interface for creating11591and updating database files.11592As an example, I'll create a database11593that contains captions for image files.11594\index{open function}11595\index{function!open}1159611597Opening a database is similar to opening other files:1159811599\begin{verbatim}11600>>> import dbm11601>>> db = dbm.open('captions', 'c')11602\end{verbatim}11603%11604The mode \verb"'c'" means that the database should be created if11605it doesn't already exist. The result is a database object11606that can be used (for most operations) like a dictionary.11607\index{database object}11608\index{object!database}1160911610When you create a new item, {\tt dbm} updates the database file.11611\index{update!database}1161211613\begin{verbatim}11614>>> db['cleese.png'] = 'Photo of John Cleese.'11615\end{verbatim}11616%11617When you access one of the items, {\tt dbm} reads the file:1161811619\begin{verbatim}11620>>> db['cleese.png']11621b'Photo of John Cleese.'11622\end{verbatim}11623%11624The result is a {\bf bytes object}, which is why it begins with {\tt11625b}. A bytes object is similar to a string in many ways. When you11626get farther into Python, the difference becomes important, but for now11627we can ignore it.11628\index{bytes object}11629\index{object!bytes}1163011631If you make another assignment to an existing key, {\tt dbm} replaces11632the old value:1163311634\begin{verbatim}11635>>> db['cleese.png'] = 'Photo of John Cleese doing a silly walk.'11636>>> db['cleese.png']11637b'Photo of John Cleese doing a silly walk.'11638\end{verbatim}11639%1164011641Some dictionary methods, like {\tt keys} and {\tt items}, don't11642work with database objects. But iteration with a {\tt for}11643loop works:11644\index{dictionary methods!dbm module}1164511646\begin{verbatim}11647for key in db:11648print(key, db[key])11649\end{verbatim}11650%11651As with other files, you should close the database when you are11652done:1165311654\begin{verbatim}11655>>> db.close()11656\end{verbatim}11657%11658\index{close method}11659\index{method!close}116601166111662\section{Pickling}11663\index{pickling}1166411665A limitation of {\tt dbm} is that the keys and values have to be11666strings or bytes. If you try to use any other type, you get an error.11667\index{pickle module} \index{module!pickle}1166811669The {\tt pickle} module can help. It translates11670almost any type of object into a string suitable for storage in a11671database, and then translates strings back into objects.1167211673{\tt pickle.dumps} takes an object as a parameter and returns11674a string representation ({\tt dumps} is short for ``dump string''):1167511676\begin{verbatim}11677>>> import pickle11678>>> t = [1, 2, 3]11679>>> pickle.dumps(t)11680b'\x80\x03]q\x00(K\x01K\x02K\x03e.'11681\end{verbatim}11682%11683The format isn't obvious to human readers; it is meant to be11684easy for {\tt pickle} to interpret. {\tt pickle.loads}11685(``load string'') reconstitutes the object:1168611687\begin{verbatim}11688>>> t1 = [1, 2, 3]11689>>> s = pickle.dumps(t1)11690>>> t2 = pickle.loads(s)11691>>> t211692[1, 2, 3]11693\end{verbatim}11694%11695Although the new object has the same value as the old, it is11696not (in general) the same object:1169711698\begin{verbatim}11699>>> t1 == t211700True11701>>> t1 is t211702False11703\end{verbatim}11704%11705In other words, pickling and then unpickling has the same effect11706as copying the object.1170711708You can use {\tt pickle} to store non-strings in a database.11709In fact, this combination is so common that it has been11710encapsulated in a module called {\tt shelve}.11711\index{shelve module}11712\index{module!shelve}117131171411715\section{Pipes}11716\index{shell}11717\index{pipe}1171811719Most operating systems provide a command-line interface,11720also known as a {\bf shell}. Shells usually provide commands11721to navigate the file system and launch applications. For11722example, in Unix you can change directories with {\tt cd},11723display the contents of a directory with {\tt ls}, and launch11724a web browser by typing (for example) {\tt firefox}.11725\index{ls (Unix command)}11726\index{Unix command!ls}1172711728Any program that you can launch from the shell can also be11729launched from Python using a {\bf pipe object}, which11730represents a running program.1173111732For example, the Unix command {\tt ls -l} normally displays the11733contents of the current directory in long format. You can11734launch {\tt ls} with {\tt os.popen}\footnote{{\tt popen} is deprecated11735now, which means we are supposed to stop using it and start using11736the {\tt subprocess} module. But for simple cases, I find11737{\tt subprocess} more complicated than necessary. So I am going11738to keep using {\tt popen} until they take it away.}:11739\index{popen function}11740\index{function!popen}1174111742\begin{verbatim}11743>>> cmd = 'ls -l'11744>>> fp = os.popen(cmd)11745\end{verbatim}11746%11747The argument is a string that contains a shell command. The11748return value is an object that behaves like an open11749file. You can read the output from the {\tt ls} process one11750line at a time with {\tt readline} or get the whole thing at11751once with {\tt read}:11752\index{readline method}11753\index{method!readline}11754\index{read method}11755\index{method!read}1175611757\begin{verbatim}11758>>> res = fp.read()11759\end{verbatim}11760%11761When you are done, you close the pipe like a file:11762\index{close method}11763\index{method!close}1176411765\begin{verbatim}11766>>> stat = fp.close()11767>>> print(stat)11768None11769\end{verbatim}11770%11771The return value is the final status of the {\tt ls} process;11772{\tt None} means that it ended normally (with no errors).1177311774For example, most Unix systems provide a command called {\tt md5sum}11775that reads the contents of a file and computes a ``checksum''.11776You can read about MD5 at \url{http://en.wikipedia.org/wiki/Md5}. This11777command provides an efficient way to check whether two files11778have the same contents. The probability that different contents11779yield the same checksum is very small (that is, unlikely to happen11780before the universe collapses).11781\index{md5}11782\index{checksum}1178311784You can use a pipe to run {\tt md5sum} from Python and get the result:1178511786\begin{verbatim}11787>>> filename = 'book.tex'11788>>> cmd = 'md5sum ' + filename11789>>> fp = os.popen(cmd)11790>>> res = fp.read()11791>>> stat = fp.close()11792>>> print(res)117931e0033f0ed0656636de0d75144ba32e0 book.tex11794>>> print(stat)11795None11796\end{verbatim}11797117981179911800\section{Writing modules}11801\label{modules}11802\index{module, writing}11803\index{word count}1180411805Any file that contains Python code can be imported as a module.11806For example, suppose you have a file named {\tt wc.py} with the following11807code:1180811809\begin{verbatim}11810def linecount(filename):11811count = 011812for line in open(filename):11813count += 111814return count1181511816print(linecount('wc.py'))11817\end{verbatim}11818%11819If you run this program, it reads itself and prints the number11820of lines in the file, which is 7.11821You can also import it like this:1182211823\begin{verbatim}11824>>> import wc11825711826\end{verbatim}11827%11828Now you have a module object {\tt wc}:11829\index{module object}11830\index{object!module}1183111832\begin{verbatim}11833>>> wc11834<module 'wc' from 'wc.py'>11835\end{verbatim}11836%11837The module object provides \verb"linecount":1183811839\begin{verbatim}11840>>> wc.linecount('wc.py')11841711842\end{verbatim}11843%11844So that's how you write modules in Python.1184511846The only problem with this example is that when you import11847the module it runs the test code at the bottom. Normally11848when you import a module, it defines new functions but it11849doesn't run them.11850\index{import statement}11851\index{statement!import}1185211853Programs that will be imported as modules often11854use the following idiom:1185511856\begin{verbatim}11857if __name__ == '__main__':11858print(linecount('wc.py'))11859\end{verbatim}11860%11861\verb"__name__" is a built-in variable that is set when the11862program starts. If the program is running as a script,11863\verb"__name__" has the value \verb"'__main__'"; in that11864case, the test code runs. Otherwise,11865if the module is being imported, the test code is skipped.1186611867\index{name built-in variable}11868\index{main}1186911870As an exercise, type this example into a file named {\tt wc.py} and run11871it as a script. Then run the Python interpreter and11872{\tt import wc}. What is the value of \verb"__name__"11873when the module is being imported?1187411875Warning: If you import a module that has already been imported,11876Python does nothing. It does not re-read the file, even if it has11877changed.11878\index{module!reload}11879\index{reload function}11880\index{function!reload}1188111882If you want to reload a module, you can use the built-in function11883{\tt reload}, but it can be tricky, so the safest thing to do is11884restart the interpreter and then import the module again.118851188611887\section{Debugging}11888\index{debugging}11889\index{whitespace}1189011891When you are reading and writing files, you might run into problems11892with whitespace. These errors can be hard to debug because spaces,11893tabs and newlines are normally invisible:1189411895\begin{verbatim}11896>>> s = '1 2\t 3\n 4'11897>>> print(s)118981 2 311899411900\end{verbatim}11901\index{repr function}11902\index{function!repr}11903\index{string representation}1190411905The built-in function {\tt repr} can help. It takes any object as an11906argument and returns a string representation of the object. For11907strings, it represents whitespace11908characters with backslash sequences:1190911910\begin{verbatim}11911>>> print(repr(s))11912'1 2\t 3\n 4'11913\end{verbatim}1191411915This can be helpful for debugging.1191611917One other problem you might run into is that different systems11918use different characters to indicate the end of a line. Some11919systems use a newline, represented \verb"\n". Others use11920a return character, represented \verb"\r". Some use both.11921If you move files between different systems, these inconsistencies11922can cause problems.11923\index{end of line character}1192411925For most systems, there are applications to convert from one11926format to another. You can find them (and read more about this11927issue) at \url{http://en.wikipedia.org/wiki/Newline}. Or, of course, you11928could write one yourself.119291193011931\section{Glossary}1193211933\begin{description}1193411935\item[persistent:] Pertaining to a program that runs indefinitely11936and keeps at least some of its data in permanent storage.11937\index{persistence}1193811939\item[format operator:] An operator, {\tt \%}, that takes a format11940string and a tuple and generates a string that includes11941the elements of the tuple formatted as specified by the format string.11942\index{format operator}11943\index{operator!format}1194411945\item[format string:] A string, used with the format operator, that11946contains format sequences.11947\index{format string}1194811949\item[format sequence:] A sequence of characters in a format string,11950like {\tt \%d}, that specifies how a value should be formatted.11951\index{format sequence}1195211953\item[text file:] A sequence of characters stored in permanent11954storage like a hard drive.11955\index{text file}1195611957\item[directory:] A named collection of files, also called a folder.11958\index{directory}1195911960\item[path:] A string that identifies a file.11961\index{path}1196211963\item[relative path:] A path that starts from the current directory.11964\index{relative path}1196511966\item[absolute path:] A path that starts from the topmost directory11967in the file system.11968\index{absolute path}1196911970\item[catch:] To prevent an exception from terminating11971a program using the {\tt try}11972and {\tt except} statements.11973\index{catch}1197411975\item[database:] A file whose contents are organized like a dictionary11976with keys that correspond to values.11977\index{database}1197811979\item[bytes object:] An object similar to a string.11980\index{bytes object}11981\index{object!bytes}1198211983\item[shell:] A program that allows users to type commands and then11984executes them by starting other programs.11985\index{shell}1198611987\item[pipe object:] An object that represents a running program, allowing11988a Python program to run commands and read the results.11989\index{pipe object}11990\index{object!pipe}1199111992\end{description}119931199411995\section{Exercises}1199611997\begin{exercise}1199811999Write a function called {\tt sed} that takes as arguments a pattern string,12000a replacement string, and two filenames; it should read the first file12001and write the contents into the second file (creating it if12002necessary). If the pattern string appears anywhere in the file, it12003should be replaced with the replacement string.1200412005If an error occurs while opening, reading, writing or closing files,12006your program should catch the exception, print an error message, and12007exit. Solution: \url{http://thinkpython2.com/code/sed.py}.1200812009\end{exercise}120101201112012\begin{exercise}12013\index{anagram set}12014\index{set!anagram}1201512016If you download my solution to Exercise~\ref{anagrams} from12017\url{http://thinkpython2.com/code/anagram_sets.py}, you'll see that it creates12018a dictionary that maps from a sorted string of letters to the list of12019words that can be spelled with those letters. For example,12020\verb"'opst'" maps to the list12021\verb"['opts', 'post', 'pots', 'spot', 'stop', 'tops']".1202212023Write a module that imports \verb"anagram_sets" and provides12024two new functions: \verb"store_anagrams" should store the12025anagram dictionary in a ``shelf''; \verb"read_anagrams" should12026look up a word and return a list of its anagrams.12027Solution: \url{http://thinkpython2.com/code/anagram_db.py}.1202812029\end{exercise}120301203112032\begin{exercise}12033\label{checksum}12034\index{MP3}1203512036In a large collection of MP3 files, there may be more than one12037copy of the same song, stored in different directories or with12038different file names. The goal of this exercise is to search for12039duplicates.1204012041\begin{enumerate}1204212043\item Write a program that searches a directory and all of its12044subdirectories, recursively, and returns a list of complete paths12045for all files with a given suffix (like {\tt .mp3}).12046Hint: {\tt os.path} provides several useful functions for12047manipulating file and path names.12048\index{duplicate}12049\index{MD5 algorithm}12050\index{algorithm!MD5}12051\index{checksum}1205212053\item To recognize duplicates, you can use {\tt md5sum}12054to compute a ``checksum'' for each files. If two files have12055the same checksum, they probably have the same contents.12056\index{md5sum}1205712058\item To double-check, you can use the Unix command {\tt diff}.12059\index{diff}1206012061\end{enumerate}1206212063Solution: \url{http://thinkpython2.com/code/find_duplicates.py}.1206412065\end{exercise}12066120671206812069\chapter{Classes and objects}12070\label{clobjects}1207112072At this point you know how to use12073functions to organize code and12074built-in types to organize data. The next step is to learn12075``object-oriented programming'', which uses programmer-defined types12076to organize both code and data. Object-oriented programming is12077a big topic; it will take a few chapters to get there.12078\index{object-oriented programming}1207912080Code examples from this chapter are available from12081\url{http://thinkpython2.com/code/Point1.py}; solutions12082to the exercises are available from12083\url{http://thinkpython2.com/code/Point1_soln.py}.120841208512086\section{Programmer-defined types}12087\label{point}12088\index{programmer-defined type}12089\index{type!programmer-defined}1209012091We have used many of Python's built-in types; now we are going12092to define a new type. As an example, we will create a type12093called {\tt Point} that represents a point in two-dimensional12094space.12095\index{point, mathematical}1209612097In mathematical notation, points are often written in12098parentheses with a comma separating the coordinates. For example,12099$(0,0)$ represents the origin, and $(x,y)$ represents the12100point $x$ units to the right and $y$ units up from the origin.1210112102There are several ways we might represent points in Python:1210312104\begin{itemize}1210512106\item We could store the coordinates separately in two12107variables, {\tt x} and {\tt y}.1210812109\item We could store the coordinates as elements in a list12110or tuple.1211112112\item We could create a new type to represent points as12113objects.1211412115\end{itemize}12116\index{representation}1211712118Creating a new type12119is more complicated than the other options, but12120it has advantages that will be apparent soon.1212112122A programmer-defined type is also called a {\bf class}.12123A class definition looks like this:12124\index{class}12125\index{object!class}12126\index{class definition}12127\index{definition!class}1212812129\begin{verbatim}12130class Point:12131"""Represents a point in 2-D space."""12132\end{verbatim}12133%12134The header indicates that the new class is called {\tt Point}.12135The body is a docstring that explains what the class is for.12136You can define variables and methods inside a class definition,12137but we will get back to that later.12138\index{Point class}12139\index{class!Point}12140\index{docstring}1214112142Defining a class named {\tt Point} creates a {\bf class object}.1214312144\begin{verbatim}12145>>> Point12146<class '__main__.Point'>12147\end{verbatim}12148%12149Because {\tt Point} is defined at the top level, its ``full12150name'' is \verb"__main__.Point".12151\index{object!class}12152\index{class object}1215312154The class object is like a factory for creating objects. To create a12155Point, you call {\tt Point} as if it were a function.1215612157\begin{verbatim}12158>>> blank = Point()12159>>> blank12160<__main__.Point object at 0xb7e9d3ac>12161\end{verbatim}12162%12163The return value is a reference to a Point object, which we12164assign to {\tt blank}.1216512166Creating a new object is called12167{\bf instantiation}, and the object is an {\bf instance} of12168the class.12169\index{instance}12170\index{instantiation}1217112172When you print an instance, Python tells you what class it12173belongs to and where it is stored in memory (the prefix12174{\tt 0x} means that the following number is in hexadecimal).12175\index{hexadecimal}1217612177Every object is an instance of some class, so ``object'' and12178``instance'' are interchangeable. But in this chapter I use12179``instance'' to indicate that I am talking about a programmer-defined12180type.121811218212183\section{Attributes}12184\label{attributes}12185\index{instance attribute}12186\index{attribute!instance}12187\index{dot notation}1218812189You can assign values to an instance using dot notation:1219012191\begin{verbatim}12192>>> blank.x = 3.012193>>> blank.y = 4.012194\end{verbatim}12195%12196This syntax is similar to the syntax for selecting a variable from a12197module, such as {\tt math.pi} or {\tt string.whitespace}. In this case,12198though, we are assigning values to named elements of an object.12199These elements are called {\bf attributes}.1220012201As a noun, ``AT-trib-ute'' is pronounced with emphasis on the first12202syllable, as opposed to ``a-TRIB-ute'', which is a verb.1220312204Figure~\ref{fig.point} is a state diagram that shows the result of these assignments.12205A state diagram that shows an object and its attributes is12206called an {\bf object diagram}.12207\index{state diagram}12208\index{diagram!state}12209\index{object diagram}12210\index{diagram!object}1221112212\begin{figure}12213\centerline12214{\includegraphics[scale=0.8]{figs/point.pdf}}12215\caption{Object diagram.}12216\label{fig.point}12217\end{figure}1221812219The variable {\tt blank} refers to a Point object, which12220contains two attributes. Each attribute refers to a12221floating-point number.1222212223You can read the value of an attribute using the same syntax:1222412225\begin{verbatim}12226>>> blank.y122274.012228>>> x = blank.x12229>>> x122303.012231\end{verbatim}12232%12233The expression {\tt blank.x} means, ``Go to the object {\tt blank}12234refers to and get the value of {\tt x}.'' In the example, we assign that12235value to a variable named {\tt x}. There is no conflict between12236the variable {\tt x} and the attribute {\tt x}.1223712238You can use dot notation as part of any expression. For example:1223912240\begin{verbatim}12241>>> '(%g, %g)' % (blank.x, blank.y)12242'(3.0, 4.0)'12243>>> distance = math.sqrt(blank.x**2 + blank.y**2)12244>>> distance122455.012246\end{verbatim}12247%12248You can pass an instance as an argument in the usual way.12249For example:12250\index{instance!as argument}1225112252\begin{verbatim}12253def print_point(p):12254print('(%g, %g)' % (p.x, p.y))12255\end{verbatim}12256%12257\verb"print_point" takes a point as an argument and displays it in12258mathematical notation. To invoke it, you can pass {\tt blank} as12259an argument:1226012261\begin{verbatim}12262>>> print_point(blank)12263(3.0, 4.0)12264\end{verbatim}12265%12266Inside the function, {\tt p} is an alias for {\tt blank}, so if12267the function modifies {\tt p}, {\tt blank} changes.12268\index{aliasing}1226912270As an exercise, write a function called \verb"distance_between_points"12271that takes two Points as arguments and returns the distance between12272them.122731227412275\section{Rectangles}12276\label{rectangles}1227712278Sometimes it is obvious what the attributes of an object should be,12279but other times you have to make decisions. For example, imagine you12280are designing a class to represent rectangles. What attributes would12281you use to specify the location and size of a rectangle? You can12282ignore angle; to keep things simple, assume that the rectangle is12283either vertical or horizontal.12284\index{representation}1228512286There are at least two possibilities:1228712288\begin{itemize}1228912290\item You could specify one corner of the rectangle12291(or the center), the width, and the height.1229212293\item You could specify two opposing corners.1229412295\end{itemize}1229612297At this point it is hard to say whether either is better than12298the other, so we'll implement the first one, just as an example.12299\index{Rectangle class}12300\index{class!Rectangle}1230112302Here is the class definition:1230312304\begin{verbatim}12305class Rectangle:12306"""Represents a rectangle.1230712308attributes: width, height, corner.12309"""12310\end{verbatim}12311%12312The docstring lists the attributes: {\tt width} and12313{\tt height} are numbers; {\tt corner} is a Point object that12314specifies the lower-left corner.1231512316To represent a rectangle, you have to instantiate a Rectangle12317object and assign values to the attributes:1231812319\begin{verbatim}12320box = Rectangle()12321box.width = 100.012322box.height = 200.012323box.corner = Point()12324box.corner.x = 0.012325box.corner.y = 0.012326\end{verbatim}12327%12328The expression {\tt box.corner.x} means,12329``Go to the object {\tt box} refers to and select the attribute named12330{\tt corner}; then go to that object and select the attribute named12331{\tt x}.''1233212333\begin{figure}12334\centerline12335{\includegraphics[scale=0.8]{figs/rectangle.pdf}}12336\caption{Object diagram.}12337\label{fig.rectangle}12338\end{figure}123391234012341Figure~\ref{fig.rectangle} shows the state of this object.12342An object that is an attribute of another object is {\bf embedded}.12343\index{state diagram}12344\index{diagram!state}12345\index{object diagram}12346\index{diagram!object}12347\index{embedded object}12348\index{object!embedded}123491235012351\section{Instances as return values}12352\index{instance!as return value}12353\index{return value}1235412355Functions can return instances. For example, \verb"find_center"12356takes a {\tt Rectangle} as an argument and returns a {\tt Point}12357that contains the coordinates of the center of the {\tt Rectangle}:1235812359\begin{verbatim}12360def find_center(rect):12361p = Point()12362p.x = rect.corner.x + rect.width/212363p.y = rect.corner.y + rect.height/212364return p12365\end{verbatim}12366%12367Here is an example that passes {\tt box} as an argument and assigns12368the resulting Point to {\tt center}:1236912370\begin{verbatim}12371>>> center = find_center(box)12372>>> print_point(center)12373(50, 100)12374\end{verbatim}12375%1237612377\section{Objects are mutable}12378\index{object!mutable}12379\index{mutability}1238012381You can change the state of an object by making an assignment to one of12382its attributes. For example, to change the size of a rectangle12383without changing its position, you can modify the values of {\tt12384width} and {\tt height}:1238512386\begin{verbatim}12387box.width = box.width + 5012388box.height = box.height + 10012389\end{verbatim}12390%12391You can also write functions that modify objects. For example,12392\verb"grow_rectangle" takes a Rectangle object and two numbers,12393{\tt dwidth} and {\tt dheight}, and adds the numbers to the12394width and height of the rectangle:1239512396\begin{verbatim}12397def grow_rectangle(rect, dwidth, dheight):12398rect.width += dwidth12399rect.height += dheight12400\end{verbatim}12401%12402Here is an example that demonstrates the effect:1240312404\begin{verbatim}12405>>> box.width, box.height12406(150.0, 300.0)12407>>> grow_rectangle(box, 50, 100)12408>>> box.width, box.height12409(200.0, 400.0)12410\end{verbatim}12411%12412Inside the function, {\tt rect} is an12413alias for {\tt box}, so when the function modifies {\tt rect},12414{\tt box} changes.1241512416As an exercise, write a function named \verb"move_rectangle" that takes12417a Rectangle and two numbers named {\tt dx} and {\tt dy}. It12418should change the location of the rectangle by adding {\tt dx}12419to the {\tt x} coordinate of {\tt corner} and adding {\tt dy}12420to the {\tt y} coordinate of {\tt corner}.124211242212423\section{Copying}12424\label{copying}12425\index{aliasing}1242612427Aliasing can make a program difficult to read because changes12428in one place might have unexpected effects in another place.12429It is hard to keep track of all the variables that might refer12430to a given object.12431\index{copying objects}12432\index{object!copying}12433\index{copy module}12434\index{module!copy}1243512436Copying an object is often an alternative to aliasing.12437The {\tt copy} module contains a function called {\tt copy} that12438can duplicate any object:1243912440\begin{verbatim}12441>>> p1 = Point()12442>>> p1.x = 3.012443>>> p1.y = 4.01244412445>>> import copy12446>>> p2 = copy.copy(p1)12447\end{verbatim}12448%12449{\tt p1} and {\tt p2} contain the same data, but they are12450not the same Point.1245112452\begin{verbatim}12453>>> print_point(p1)12454(3, 4)12455>>> print_point(p2)12456(3, 4)12457>>> p1 is p212458False12459>>> p1 == p212460False12461\end{verbatim}12462%12463The {\tt is} operator indicates that {\tt p1} and {\tt p2} are not the12464same object, which is what we expected. But you might have expected12465{\tt ==} to yield {\tt True} because these points contain the same12466data. In that case, you will be disappointed to learn that for12467instances, the default behavior of the {\tt ==} operator is the same12468as the {\tt is} operator; it checks object identity, not object12469equivalence. That's because for programmer-defined types, Python doesn't12470know what should be considered equivalent. At least, not yet.12471\index{is operator}12472\index{operator!is}12473\index{identity}12474\index{equivalence}1247512476If you use {\tt copy.copy} to duplicate a Rectangle, you will find12477that it copies the Rectangle object but not the embedded Point.12478\index{embedded object!copying}1247912480\begin{verbatim}12481>>> box2 = copy.copy(box)12482>>> box2 is box12483False12484>>> box2.corner is box.corner12485True12486\end{verbatim}1248712488\begin{figure}12489\centerline12490{\includegraphics[scale=0.8]{figs/rectangle2.pdf}}12491\caption{Object diagram.}12492\label{fig.rectangle2}12493\end{figure}1249412495Figure~\ref{fig.rectangle2} shows what the object diagram looks like.12496\index{state diagram}12497\index{diagram!state}12498\index{object diagram}12499\index{diagram!object}12500This operation is called a {\bf shallow copy} because it copies the12501object and any references it contains, but not the embedded objects.12502\index{shallow copy}12503\index{copy!shallow}1250412505For most applications, this is not what you want. In this example,12506invoking \verb"grow_rectangle" on one of the Rectangles would not12507affect the other, but invoking \verb"move_rectangle" on either would12508affect both! This behavior is confusing and error-prone.12509\index{deep copy}12510\index{copy!deep}1251112512Fortunately, the {\tt copy} module provides a method named {\tt12513deepcopy} that copies not only the object but also12514the objects it refers to, and the objects {\em they} refer to,12515and so on.12516You will not be surprised to learn that this operation is12517called a {\bf deep copy}.12518\index{deepcopy function}12519\index{function!deepcopy}1252012521\begin{verbatim}12522>>> box3 = copy.deepcopy(box)12523>>> box3 is box12524False12525>>> box3.corner is box.corner12526False12527\end{verbatim}12528%12529{\tt box3} and {\tt box} are completely separate objects.1253012531As an exercise, write a version of \verb"move_rectangle" that creates and12532returns a new Rectangle instead of modifying the old one.125331253412535\section{Debugging}12536\label{hasattr}12537\index{debugging}1253812539When you start working with objects, you are likely to encounter12540some new exceptions. If you try to access an attribute12541that doesn't exist, you get an {\tt AttributeError}:12542\index{exception!AttributeError}12543\index{AttributeError}1254412545\begin{verbatim}12546>>> p = Point()12547>>> p.x = 312548>>> p.y = 412549>>> p.z12550AttributeError: Point instance has no attribute 'z'12551\end{verbatim}12552%12553If you are not sure what type an object is, you can ask:12554\index{type function}12555\index{function!type}1255612557\begin{verbatim}12558>>> type(p)12559<class '__main__.Point'>12560\end{verbatim}12561%12562You can also use {\tt isinstance} to check whether an object12563is an instance of a class:12564\index{isinstance function}12565\index{function!isinstance}1256612567\begin{verbatim}12568>>> isinstance(p, Point)12569True12570\end{verbatim}12571%12572If you are not sure whether an object has a particular attribute,12573you can use the built-in function {\tt hasattr}:12574\index{hasattr function}12575\index{function!hasattr}1257612577\begin{verbatim}12578>>> hasattr(p, 'x')12579True12580>>> hasattr(p, 'z')12581False12582\end{verbatim}12583%12584The first argument can be any object; the second argument is a {\em12585string} that contains the name of the attribute.12586\index{attribute}1258712588You can also use a {\tt try} statement to see if the object has the12589attributes you need:12590\index{try statement}12591\index{statement!try}1259212593\begin{verbatim}12594try:12595x = p.x12596except AttributeError:12597x = 012598\end{verbatim}1259912600This approach can make it easier to write functions that work with12601different types; more on that topic is12602coming up in Section~\ref{polymorphism}.126031260412605\section{Glossary}1260612607\begin{description}1260812609\item[class:] A programmer-defined type. A class definition creates a new12610class object.12611\index{class}12612\index{programmer-defined type}12613\index{type!programmer-defined}1261412615\item[class object:] An object that contains information about a12616programmer-defined type. The class object can be used to create instances12617of the type.12618\index{class object}12619\index{object!class}1262012621\item[instance:] An object that belongs to a class.12622\index{instance}1262312624\item[instantiate:] To create a new object.12625\index{instantiate}1262612627\item[attribute:] One of the named values associated with an object.12628\index{attribute!instance}12629\index{instance attribute}1263012631\item[embedded object:] An object that is stored as an attribute12632of another object.12633\index{embedded object}12634\index{object!embedded}1263512636\item[shallow copy:] To copy the contents of an object, including12637any references to embedded objects;12638implemented by the {\tt copy} function in the {\tt copy} module.12639\index{shallow copy}1264012641\item[deep copy:] To copy the contents of an object as well as any12642embedded objects, and any objects embedded in them, and so on;12643implemented by the {\tt deepcopy} function in the {\tt copy} module.12644\index{deep copy}1264512646\item[object diagram:] A diagram that shows objects, their12647attributes, and the values of the attributes.12648\index{object diagram}12649\index{diagram!object}1265012651\end{description}126521265312654\section{Exercises}1265512656\begin{exercise}1265712658Write a definition for a class named {\tt Circle} with attributes12659{\tt center} and {\tt radius}, where {\tt center} is a Point object12660and radius is a number.1266112662Instantiate a Circle object that represents a circle with its center12663at $(150, 100)$ and radius 75.1266412665Write a function named \verb"point_in_circle" that takes a Circle and12666a Point and returns True if the Point lies in or on the boundary of12667the circle.1266812669Write a function named \verb"rect_in_circle" that takes a Circle and a12670Rectangle and returns True if the Rectangle lies entirely in or on the boundary12671of the circle.1267212673Write a function named \verb"rect_circle_overlap" that takes a Circle12674and a Rectangle and returns True if any of the corners of the Rectangle fall12675inside the circle. Or as a more challenging version, return True if12676any part of the Rectangle falls inside the circle.1267712678Solution: \url{http://thinkpython2.com/code/Circle.py}.1267912680\end{exercise}126811268212683\begin{exercise}1268412685Write a function called \verb"draw_rect" that takes a Turtle object12686and a Rectangle and uses the Turtle to draw the Rectangle. See12687Chapter~\ref{turtlechap} for examples using Turtle objects.1268812689Write a function called \verb"draw_circle" that takes a Turtle and12690a Circle and draws the Circle.1269112692Solution: \url{http://thinkpython2.com/code/draw.py}.1269312694\end{exercise}12695126961269712698\chapter{Classes and functions}12699\label{time}1270012701Now that we know how to create new types, the next12702step is to write functions that take programmer-defined objects12703as parameters and return them as results. In this chapter I12704also present ``functional programming style'' and two new12705program development plans.1270612707Code examples from this chapter are available from12708\url{http://thinkpython2.com/code/Time1.py}.12709Solutions to the exercises are at12710\url{http://thinkpython2.com/code/Time1_soln.py}.127111271212713\section{Time}12714\label{isafter}1271512716As another example of a programmer-defined type, we'll define a class12717called {\tt Time} that records the time of day. The class definition12718looks like this: \index{programmer-defined type}12719\index{type!programmer-defined} \index{Time class} \index{class!Time}1272012721\begin{verbatim}12722class Time:12723"""Represents the time of day.1272412725attributes: hour, minute, second12726"""12727\end{verbatim}12728%12729We can create a new {\tt Time} object and assign12730attributes for hours, minutes, and seconds:1273112732\begin{verbatim}12733time = Time()12734time.hour = 1112735time.minute = 5912736time.second = 3012737\end{verbatim}12738%12739The state diagram for the {\tt Time} object looks like Figure~\ref{fig.time}.12740\index{state diagram}12741\index{diagram!state}12742\index{object diagram}12743\index{diagram!object}1274412745As an exercise, write a function called \verb"print_time" that takes a12746Time object and prints it in the form {\tt hour:minute:second}.12747Hint: the format sequence \verb"'%.2d'" prints an integer using12748at least two digits, including a leading zero if necessary.1274912750Write a boolean function called \verb"is_after" that12751takes two Time objects, {\tt t1} and {\tt t2}, and12752returns {\tt True} if {\tt t1} follows {\tt t2} chronologically and12753{\tt False} otherwise. Challenge: don't use an {\tt if} statement.1275412755\begin{figure}12756\centerline12757{\includegraphics[scale=0.8]{figs/time.pdf}}12758\caption{Object diagram.}12759\label{fig.time}12760\end{figure}127611276212763\section{Pure functions}12764\index{prototype and patch}12765\index{development plan!prototype and patch}1276612767In the next few sections, we'll write two functions that add time12768values. They demonstrate two kinds of functions: pure functions and12769modifiers. They also demonstrate a development plan I'll call {\bf12770prototype and patch}, which is a way of tackling a complex problem12771by starting with a simple prototype and incrementally dealing with the12772complications.1277312774Here is a simple prototype of \verb"add_time":1277512776\begin{verbatim}12777def add_time(t1, t2):12778sum = Time()12779sum.hour = t1.hour + t2.hour12780sum.minute = t1.minute + t2.minute12781sum.second = t1.second + t2.second12782return sum12783\end{verbatim}12784%12785The function creates a new {\tt Time} object, initializes its12786attributes, and returns a reference to the new object. This is called12787a {\bf pure function} because it does not modify any of the objects12788passed to it as arguments and it has no effect,12789like displaying a value or getting user input,12790other than returning a value.12791\index{pure function}12792\index{function type!pure}1279312794To test this function, I'll create two Time objects: {\tt start}12795contains the start time of a movie, like {\em Monty Python and the12796Holy Grail}, and {\tt duration} contains the run time of the movie,12797which is one hour 35 minutes.12798\index{Monty Python and the Holy Grail}1279912800\verb"add_time" figures out when the movie will be done.1280112802\begin{verbatim}12803>>> start = Time()12804>>> start.hour = 912805>>> start.minute = 4512806>>> start.second = 01280712808>>> duration = Time()12809>>> duration.hour = 112810>>> duration.minute = 3512811>>> duration.second = 01281212813>>> done = add_time(start, duration)12814>>> print_time(done)1281510:80:0012816\end{verbatim}12817%12818The result, {\tt 10:80:00} might not be what you were hoping12819for. The problem is that this function does not deal with cases where the12820number of seconds or minutes adds up to more than sixty. When that12821happens, we have to ``carry'' the extra seconds into the minute column12822or the extra minutes into the hour column.12823\index{carrying, addition with}1282412825Here's an improved version:1282612827\begin{verbatim}12828def add_time(t1, t2):12829sum = Time()12830sum.hour = t1.hour + t2.hour12831sum.minute = t1.minute + t2.minute12832sum.second = t1.second + t2.second1283312834if sum.second >= 60:12835sum.second -= 6012836sum.minute += 11283712838if sum.minute >= 60:12839sum.minute -= 6012840sum.hour += 11284112842return sum12843\end{verbatim}12844%12845Although this function is correct, it is starting to get big.12846We will see a shorter alternative later.128471284812849\section{Modifiers}12850\label{increment}12851\index{modifier}12852\index{function type!modifier}1285312854Sometimes it is useful for a function to modify the objects it gets as12855parameters. In that case, the changes are visible to the caller.12856Functions that work this way are called {\bf modifiers}.12857\index{increment}1285812859{\tt increment}, which adds a given number of seconds to a {\tt Time}12860object, can be written naturally as a12861modifier. Here is a rough draft:1286212863\begin{verbatim}12864def increment(time, seconds):12865time.second += seconds1286612867if time.second >= 60:12868time.second -= 6012869time.minute += 11287012871if time.minute >= 60:12872time.minute -= 6012873time.hour += 112874\end{verbatim}12875%12876The first line performs the basic operation; the remainder deals12877with the special cases we saw before.12878\index{special case}1287912880Is this function correct? What happens if {\tt seconds}12881is much greater than sixty?1288212883In that case, it is not enough to carry once; we have to keep doing it12884until {\tt time.second} is less than sixty. One solution is to12885replace the {\tt if} statements with {\tt while} statements. That12886would make the function correct, but not very efficient. As an12887exercise, write a correct version of {\tt increment} that doesn't12888contain any loops.1288912890Anything that can be done with modifiers can also be done with pure12891functions. In fact, some programming languages only allow pure12892functions. There is some evidence that programs that use pure12893functions are faster to develop and less error-prone than programs12894that use modifiers. But modifiers are convenient at times,12895and functional programs tend to be less efficient.1289612897In general, I recommend that you write pure functions whenever it is12898reasonable and resort to modifiers only if there is a compelling12899advantage. This approach might be called a {\bf functional12900programming style}.12901\index{functional programming style}1290212903As an exercise, write a ``pure'' version of {\tt increment} that12904creates and returns a new Time object rather than modifying the12905parameter.129061290712908\section{Prototyping versus planning}12909\label{prototype}12910\index{prototype and patch}12911\index{development plan!prototype and patch}12912\index{planned development}12913\index{development plan!designed}1291412915The development plan I am demonstrating is called ``prototype and12916patch''. For each function, I wrote a prototype that performed the12917basic calculation and then tested it, patching errors along the12918way.1291912920This approach can be effective, especially if you don't yet have a12921deep understanding of the problem. But incremental corrections can12922generate code that is unnecessarily complicated---since it deals with12923many special cases---and unreliable---since it is hard to know if you12924have found all the errors.1292512926An alternative is {\bf designed development}, in which high-level12927insight into the problem can make the programming much easier. In12928this case, the insight is that a Time object is really a three-digit12929number in base 60 (see \url{http://en.wikipedia.org/wiki/Sexagesimal}.)! The12930{\tt second} attribute is the ``ones column'', the {\tt minute}12931attribute is the ``sixties column'', and the {\tt hour} attribute is12932the ``thirty-six hundreds column''.12933\index{sexagesimal}1293412935When we wrote \verb"add_time" and {\tt increment}, we were effectively12936doing addition in base 60, which is why we had to carry from one12937column to the next.12938\index{carrying, addition with}1293912940This observation suggests another approach to the whole problem---we12941can convert Time objects to integers and take advantage of the fact12942that the computer knows how to do integer arithmetic.1294312944Here is a function that converts Times to integers:1294512946\begin{verbatim}12947def time_to_int(time):12948minutes = time.hour * 60 + time.minute12949seconds = minutes * 60 + time.second12950return seconds12951\end{verbatim}12952%12953And here is a function that converts an integer to a Time12954(recall that {\tt divmod} divides the first argument by the second12955and returns the quotient and remainder as a tuple).12956\index{divmod}1295712958\begin{verbatim}12959def int_to_time(seconds):12960time = Time()12961minutes, time.second = divmod(seconds, 60)12962time.hour, time.minute = divmod(minutes, 60)12963return time12964\end{verbatim}12965%12966You might have to think a bit, and run some tests, to convince12967yourself that these functions are correct. One way to test them is to12968check that \verb"time_to_int(int_to_time(x)) == x" for many values of12969{\tt x}. This is an example of a consistency check.12970\index{consistency check}1297112972Once you are convinced they are correct, you can use them to12973rewrite \verb"add_time":1297412975\begin{verbatim}12976def add_time(t1, t2):12977seconds = time_to_int(t1) + time_to_int(t2)12978return int_to_time(seconds)12979\end{verbatim}12980%12981This version is shorter than the original, and easier to verify. As12982an exercise, rewrite {\tt increment} using \verb"time_to_int" and12983\verb"int_to_time".1298412985In some ways, converting from base 60 to base 10 and back is harder12986than just dealing with times. Base conversion is more abstract; our12987intuition for dealing with time values is better.1298812989But if we have the insight to treat times as base 60 numbers and make12990the investment of writing the conversion functions (\verb"time_to_int"12991and \verb"int_to_time"), we get a program that is shorter, easier to12992read and debug, and more reliable.1299312994It is also easier to add features later. For example, imagine12995subtracting two Times to find the duration between them. The12996naive approach would be to implement subtraction with borrowing.12997Using the conversion functions would be easier and more likely to be12998correct.12999\index{subtraction with borrowing}13000\index{borrowing, subtraction with}13001\index{generalization}1300213003Ironically, sometimes making a problem harder (or more general) makes it13004easier (because there are fewer special cases and fewer opportunities13005for error).130061300713008\section{Debugging}13009\index{debugging}1301013011A Time object is well-formed if the values of {\tt minute} and {\tt13012second} are between 0 and 60 (including 0 but not 60) and if13013{\tt hour} is positive. {\tt hour} and {\tt minute} should be13014integral values, but we might allow {\tt second} to have a13015fraction part.13016\index{invariant}1301713018Requirements like these are called {\bf invariants} because13019they should always be true. To put it a different way, if they13020are not true, something has gone wrong.1302113022Writing code to check invariants can help detect errors13023and find their causes. For example, you might have a function13024like \verb"valid_time" that takes a Time object and returns13025{\tt False} if it violates an invariant:1302613027\begin{verbatim}13028def valid_time(time):13029if time.hour < 0 or time.minute < 0 or time.second < 0:13030return False13031if time.minute >= 60 or time.second >= 60:13032return False13033return True13034\end{verbatim}13035%13036At the beginning of each function you could check the13037arguments to make sure they are valid:13038\index{raise statement}13039\index{statement!raise}1304013041\begin{verbatim}13042def add_time(t1, t2):13043if not valid_time(t1) or not valid_time(t2):13044raise ValueError('invalid Time object in add_time')13045seconds = time_to_int(t1) + time_to_int(t2)13046return int_to_time(seconds)13047\end{verbatim}13048%13049Or you could use an {\bf assert statement}, which checks a given invariant13050and raises an exception if it fails:13051\index{assert statement}13052\index{statement!assert}1305313054\begin{verbatim}13055def add_time(t1, t2):13056assert valid_time(t1) and valid_time(t2)13057seconds = time_to_int(t1) + time_to_int(t2)13058return int_to_time(seconds)13059\end{verbatim}13060%13061{\tt assert} statements are useful because they distinguish13062code that deals with normal conditions from code13063that checks for errors.130641306513066\section{Glossary}1306713068\begin{description}1306913070\item[prototype and patch:] A development plan that involves13071writing a rough draft of a program, testing, and correcting errors as13072they are found.13073\index{prototype and patch}1307413075\item[designed development:] A development plan that involves13076high-level insight into the problem and more planning than incremental13077development or prototype development.13078\index{designed development}1307913080\item[pure function:] A function that does not modify any of the objects it13081receives as arguments. Most pure functions are fruitful.13082\index{pure function}1308313084\item[modifier:] A function that changes one or more of the objects it13085receives as arguments. Most modifiers are void; that is, they13086return {\tt None}. \index{modifier}1308713088\item[functional programming style:] A style of program design in which the13089majority of functions are pure.13090\index{functional programming style}1309113092\item[invariant:] A condition that should always be true during the13093execution of a program.13094\index{invariant}1309513096\item[assert statement:] A statement that check a condition and raises13097an exception if it fails.13098\index{assert statement}13099\index{statement!assert}1310013101\end{description}131021310313104\section{Exercises}1310513106Code examples from this chapter are available from13107\url{http://thinkpython2.com/code/Time1.py}; solutions to the13108exercises are available from \url{http://thinkpython2.com/code/Time1_soln.py}.1310913110\begin{exercise}1311113112Write a function called \verb"mul_time" that takes a Time object13113and a number and returns a new Time object that contains13114the product of the original Time and the number.1311513116Then use \verb"mul_time" to write a function that takes a Time13117object that represents the finishing time in a race, and a number13118that represents the distance, and returns a Time object that represents13119the average pace (time per mile).13120\index{running pace}1312113122\end{exercise}131231312413125\begin{exercise}13126\index{datetime module}13127\index{module!datetime}1312813129The {\tt datetime} module provides {\tt time} objects13130that are similar to the Time objects in this chapter, but13131they provide a rich set of methods and operators. Read the13132documentation at \url{http://docs.python.org/3/library/datetime.html}.1313313134\begin{enumerate}1313513136\item Use the {\tt datetime} module to write a program that gets the13137current date and prints the day of the week.1313813139\item Write a program that takes a birthday as input and prints the13140user's age and the number of days, hours, minutes and seconds until13141their next birthday.13142\index{birthday}1314313144\item For two people born on different days, there is a day when one13145is twice as old as the other. That's their Double Day. Write a13146program that takes two birth dates and computes their Double Day.1314713148\item For a little more challenge, write the more general version that13149computes the day when one person is $n$ times older than the other.13150\index{Double Day}1315113152\end{enumerate}1315313154Solution: \url{http://thinkpython2.com/code/double.py}1315513156\end{exercise}131571315813159\chapter{Classes and methods}1316013161Although we are using some of Python's object-oriented features,13162the programs from the last two chapters are not really13163object-oriented because they don't represent the relationships13164between programmer-defined types and the functions that operate13165on them. The next step is to transform those functions into13166methods that make the relationships explicit.1316713168Code examples from this chapter are available from13169\url{http://thinkpython2.com/code/Time2.py}, and solutions13170to the exercises are in \url{http://thinkpython2.com/code/Point2_soln.py}.131711317213173\section{Object-oriented features}13174\index{object-oriented programming}1317513176Python is an {\bf object-oriented programming language}, which means13177that it provides features that support object-oriented13178programming, which has these defining characteristics:1317913180\begin{itemize}1318113182\item Programs include class and method definitions.1318313184\item Most of the computation is expressed in terms of operations on13185objects.1318613187\item Objects often represent things13188in the real world, and methods often13189correspond to the ways things in the real world interact.1319013191\end{itemize}1319213193For example, the {\tt Time} class defined in Chapter~\ref{time}13194corresponds to the way people record the time of day, and the13195functions we defined correspond to the kinds of things people do with13196times. Similarly, the {\tt Point} and {\tt Rectangle} classes13197in Chapter~\ref{clobjects}13198correspond to the mathematical concepts of a point and a rectangle.1319913200So far, we have not taken advantage of the features Python provides to13201support object-oriented programming. These13202features are not strictly necessary; most of them provide13203alternative syntax for things we have already done. But in many cases,13204the alternative is more concise and more accurately conveys the13205structure of the program.1320613207For example, in {\tt Time1.py} there is no obvious13208connection between the class definition and the function definitions13209that follow. With some examination, it is apparent that every function13210takes at least one {\tt Time} object as an argument.13211\index{method}13212\index{function}1321313214This observation is the motivation for {\bf methods}; a method is13215a function that is associated with a particular class.13216We have seen methods for strings, lists, dictionaries and tuples.13217In this chapter, we will define methods for programmer-defined types.13218\index{syntax}13219\index{semantics}13220\index{programmer-defined type}13221\index{type!programmer-defined}1322213223Methods are semantically the same as functions, but there are13224two syntactic differences:1322513226\begin{itemize}1322713228\item Methods are defined inside a class definition in order13229to make the relationship between the class and the method explicit.1323013231\item The syntax for invoking a method is different from the13232syntax for calling a function.1323313234\end{itemize}1323513236In the next few sections, we will take the functions from the previous13237two chapters and transform them into methods. This transformation is13238purely mechanical; you can do it by following a sequence of13239steps. If you are comfortable converting from one form to another,13240you will be able to choose the best form for whatever you are doing.132411324213243\section{Printing objects}13244\index{object!printing}1324513246In Chapter~\ref{time}, we defined a class named13247{\tt Time} and in Section~\ref{isafter}, you13248wrote a function named \verb"print_time":1324913250\begin{verbatim}13251class Time:13252"""Represents the time of day."""1325313254def print_time(time):13255print('%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second))13256\end{verbatim}13257%13258To call this function, you have to pass a {\tt Time} object as an13259argument:1326013261\begin{verbatim}13262>>> start = Time()13263>>> start.hour = 913264>>> start.minute = 4513265>>> start.second = 0013266>>> print_time(start)1326709:45:0013268\end{verbatim}13269%13270To make \verb"print_time" a method, all we have to do is13271move the function definition inside the class definition. Notice13272the change in indentation.13273\index{indentation}1327413275\begin{verbatim}13276class Time:13277def print_time(time):13278print('%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second))13279\end{verbatim}13280%13281Now there are two ways to call \verb"print_time". The first13282(and less common) way is to use function syntax:13283\index{function syntax}13284\index{dot notation}1328513286\begin{verbatim}13287>>> Time.print_time(start)1328809:45:0013289\end{verbatim}13290%13291In this use of dot notation, {\tt Time} is the name of the class,13292and \verb"print_time" is the name of the method. {\tt start} is13293passed as a parameter.1329413295The second (and more concise) way is to use method syntax:13296\index{method syntax}1329713298\begin{verbatim}13299>>> start.print_time()1330009:45:0013301\end{verbatim}13302%13303In this use of dot notation, \verb"print_time" is the name of the13304method (again), and {\tt start} is the object the method is13305invoked on, which is called the {\bf subject}. Just as the13306subject of a sentence is what the sentence is about, the subject13307of a method invocation is what the method is about.13308\index{subject}1330913310Inside the method, the subject is assigned to the first13311parameter, so in this case {\tt start} is assigned13312to {\tt time}.13313\index{self (parameter name)}13314\index{parameter!self}1331513316By convention, the first parameter of a method is13317called {\tt self}, so it would be more common to write13318\verb"print_time" like this:1331913320\begin{verbatim}13321class Time:13322def print_time(self):13323print('%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second))13324\end{verbatim}13325%13326The reason for this convention is an implicit metaphor:13327\index{metaphor, method invocation}1332813329\begin{itemize}1333013331\item The syntax for a function call, \verb"print_time(start)",13332suggests that the function is the active agent. It says something13333like, ``Hey \verb"print_time"! Here's an object for you to print.''1333413335\item In object-oriented programming, the objects are the active13336agents. A method invocation like \verb"start.print_time()" says13337``Hey {\tt start}! Please print yourself.''1333813339\end{itemize}1334013341This change in perspective might be more polite, but it is not obvious13342that it is useful. In the examples we have seen so far, it may not13343be. But sometimes shifting responsibility from the functions onto the13344objects makes it possible to write more versatile functions (or13345methods), and makes it easier to maintain and reuse code.1334613347As an exercise, rewrite \verb"time_to_int" (from13348Section~\ref{prototype}) as a method. You might be tempted to13349rewrite \verb"int_to_time" as a method, too, but that doesn't13350really make sense because there would be no object to invoke13351it on.133521335313354\section{Another example}13355\index{increment}1335613357Here's a version of {\tt increment} (from Section~\ref{increment})13358rewritten as a method:1335913360\begin{verbatim}13361# inside class Time:1336213363def increment(self, seconds):13364seconds += self.time_to_int()13365return int_to_time(seconds)13366\end{verbatim}13367%13368This version assumes that \verb"time_to_int" is written13369as a method. Also, note that13370it is a pure function, not a modifier.1337113372Here's how you would invoke {\tt increment}:1337313374\begin{verbatim}13375>>> start.print_time()1337609:45:0013377>>> end = start.increment(1337)13378>>> end.print_time()1337910:07:1713380\end{verbatim}13381%13382The subject, {\tt start}, gets assigned to the first parameter,13383{\tt self}. The argument, {\tt 1337}, gets assigned to the13384second parameter, {\tt seconds}.1338513386This mechanism can be confusing, especially if you make an error.13387For example, if you invoke {\tt increment} with two arguments, you13388get:13389\index{exception!TypeError}13390\index{TypeError}1339113392\begin{verbatim}13393>>> end = start.increment(1337, 460)13394TypeError: increment() takes 2 positional arguments but 3 were given13395\end{verbatim}13396%13397The error message is initially confusing, because there are13398only two arguments in parentheses. But the subject is also13399considered an argument, so all together that's three.1340013401By the way, a {\bf positional argument} is an argument that13402doesn't have a parameter name; that is, it is not a keyword13403argument. In this function call:13404\index{positional argument}13405\index{argument!positional}1340613407\begin{verbatim}13408sketch(parrot, cage, dead=True)13409\end{verbatim}1341013411{\tt parrot} and {\tt cage} are positional, and {\tt dead} is13412a keyword argument.134131341413415\section{A more complicated example}1341613417Rewriting \verb"is_after" (from Section~\ref{isafter}) is slightly13418more complicated because it takes two Time objects as parameters. In13419this case it is conventional to name the first parameter {\tt self}13420and the second parameter {\tt other}: \index{other (parameter name)}13421\index{parameter!other}1342213423\begin{verbatim}13424# inside class Time:1342513426def is_after(self, other):13427return self.time_to_int() > other.time_to_int()13428\end{verbatim}13429%13430To use this method, you have to invoke it on one object and pass13431the other as an argument:1343213433\begin{verbatim}13434>>> end.is_after(start)13435True13436\end{verbatim}13437%13438One nice thing about this syntax is that it almost reads13439like English: ``end is after start?''134401344113442\section{The init method}13443\index{init method}13444\index{method!init}1344513446The init method (short for ``initialization'') is13447a special method that gets invoked when an object is instantiated.13448Its full name is \verb"__init__" (two underscore characters,13449followed by {\tt init}, and then two more underscores). An13450init method for the {\tt Time} class might look like this:1345113452\begin{verbatim}13453# inside class Time:1345413455def __init__(self, hour=0, minute=0, second=0):13456self.hour = hour13457self.minute = minute13458self.second = second13459\end{verbatim}13460%13461It is common for the parameters of \verb"__init__"13462to have the same names as the attributes. The statement1346313464\begin{verbatim}13465self.hour = hour13466\end{verbatim}13467%13468stores the value of the parameter {\tt hour} as an attribute13469of {\tt self}.13470\index{optional parameter}13471\index{parameter!optional}13472\index{default value}13473\index{override}1347413475The parameters are optional, so if you call {\tt Time} with13476no arguments, you get the default values.1347713478\begin{verbatim}13479>>> time = Time()13480>>> time.print_time()1348100:00:0013482\end{verbatim}13483%13484If you provide one argument, it overrides {\tt hour}:1348513486\begin{verbatim}13487>>> time = Time (9)13488>>> time.print_time()1348909:00:0013490\end{verbatim}13491%13492If you provide two arguments, they override {\tt hour} and13493{\tt minute}.1349413495\begin{verbatim}13496>>> time = Time(9, 45)13497>>> time.print_time()1349809:45:0013499\end{verbatim}13500%13501And if you provide three arguments, they override all three13502default values.1350313504As an exercise, write an init method for the {\tt Point} class that takes13505{\tt x} and {\tt y} as optional parameters and assigns13506them to the corresponding attributes.13507\index{Point class}13508\index{class!Point}135091351013511\section{The {\tt \_\_str\_\_} method}13512\index{str method@\_\_str\_\_ method}13513\index{method!\_\_str\_\_}1351413515\verb"__str__" is a special method, like \verb"__init__",13516that is supposed to return a string representation of an object.13517\index{string representation}1351813519For example, here is a {\tt str} method for Time objects:1352013521\begin{verbatim}13522# inside class Time:1352313524def __str__(self):13525return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)13526\end{verbatim}13527%13528When you {\tt print} an object, Python invokes the {\tt str} method:13529\index{print statement}13530\index{statement!print}1353113532\begin{verbatim}13533>>> time = Time(9, 45)13534>>> print(time)1353509:45:0013536\end{verbatim}13537%13538When I write a new class, I almost always start by writing13539\verb"__init__", which makes it easier to instantiate objects, and13540\verb"__str__", which is useful for debugging.1354113542As an exercise, write a {\tt str} method for the {\tt Point} class.13543Create a Point object and print it.135441354513546\section{Operator overloading}13547\label{operator.overloading}1354813549By defining other special methods, you can specify the behavior13550of operators on programmer-defined types. For example, if you define13551a method named \verb"__add__" for the {\tt Time} class, you can use the13552{\tt +} operator on Time objects.13553\index{programmer-defined type}13554\index{type!programmer-defined}1355513556Here is what the definition might look like:13557\index{add method}13558\index{method!add}1355913560\begin{verbatim}13561# inside class Time:1356213563def __add__(self, other):13564seconds = self.time_to_int() + other.time_to_int()13565return int_to_time(seconds)13566\end{verbatim}13567%13568And here is how you could use it:1356913570\begin{verbatim}13571>>> start = Time(9, 45)13572>>> duration = Time(1, 35)13573>>> print(start + duration)1357411:20:0013575\end{verbatim}13576%13577When you apply the {\tt +} operator to Time objects, Python invokes13578\verb"__add__". When you print the result, Python invokes13579\verb"__str__". So there is a lot happening behind the scenes!13580\index{operator overloading}1358113582Changing the behavior of an operator so that it works with13583programmer-defined types is called {\bf operator overloading}. For every13584operator in Python there is a corresponding special method, like13585\verb"__add__". For more details, see13586\url{http://docs.python.org/3/reference/datamodel.html#specialnames}.1358713588As an exercise, write an {\tt add} method for the Point class.135891359013591\section{Type-based dispatch}1359213593In the previous section we added two Time objects, but you13594also might want to add an integer to a Time object. The13595following is a version of \verb"__add__"13596that checks the type of {\tt other} and invokes either13597\verb"add_time" or {\tt increment}:1359813599\begin{verbatim}13600# inside class Time:1360113602def __add__(self, other):13603if isinstance(other, Time):13604return self.add_time(other)13605else:13606return self.increment(other)1360713608def add_time(self, other):13609seconds = self.time_to_int() + other.time_to_int()13610return int_to_time(seconds)1361113612def increment(self, seconds):13613seconds += self.time_to_int()13614return int_to_time(seconds)13615\end{verbatim}13616%13617The built-in function {\tt isinstance} takes a value and a13618class object, and returns {\tt True} if the value is an instance13619of the class.13620\index{isinstance function}13621\index{function!isinstance}1362213623If {\tt other} is a Time object, \verb"__add__" invokes13624\verb"add_time". Otherwise it assumes that the parameter13625is a number and invokes {\tt increment}. This operation is13626called a {\bf type-based dispatch} because it dispatches the13627computation to different methods based on the type of the13628arguments.13629\index{type-based dispatch}13630\index{dispatch, type-based}1363113632Here are examples that use the {\tt +} operator with different13633types:1363413635\begin{verbatim}13636>>> start = Time(9, 45)13637>>> duration = Time(1, 35)13638>>> print(start + duration)1363911:20:0013640>>> print(start + 1337)1364110:07:1713642\end{verbatim}13643%13644Unfortunately, this implementation of addition is not commutative.13645If the integer is the first operand, you get13646\index{commutativity}1364713648\begin{verbatim}13649>>> print(1337 + start)13650TypeError: unsupported operand type(s) for +: 'int' and 'instance'13651\end{verbatim}13652%13653The problem is, instead of asking the Time object to add an integer,13654Python is asking an integer to add a Time object, and it doesn't know13655how. But there is a clever solution for this problem: the13656special method \verb"__radd__", which stands for ``right-side add''.13657This method is invoked when a Time object appears on the right side of13658the {\tt +} operator. Here's the definition:13659\index{radd method}13660\index{method!radd}1366113662\begin{verbatim}13663# inside class Time:1366413665def __radd__(self, other):13666return self.__add__(other)13667\end{verbatim}13668%13669And here's how it's used:1367013671\begin{verbatim}13672>>> print(1337 + start)1367310:07:1713674\end{verbatim}13675%1367613677As an exercise, write an {\tt add} method for Points that works with13678either a Point object or a tuple:1367913680\begin{itemize}1368113682\item If the second operand is a Point, the method should return a new13683Point whose $x$ coordinate is the sum of the $x$ coordinates of the13684operands, and likewise for the $y$ coordinates.1368513686\item If the second operand is a tuple, the method should add the13687first element of the tuple to the $x$ coordinate and the second13688element to the $y$ coordinate, and return a new Point with the result.1368913690\end{itemize}1369113692136931369413695\section{Polymorphism}13696\label{polymorphism}1369713698Type-based dispatch is useful when it is necessary, but (fortunately)13699it is not always necessary. Often you can avoid it by writing functions13700that work correctly for arguments with different types.13701\index{type-based dispatch}13702\index{dispatch!type-based}1370313704Many of the functions we wrote for strings also13705work for other sequence types.13706For example, in Section~\ref{histogram}13707we used {\tt histogram} to count the number of times each letter13708appears in a word.1370913710\begin{verbatim}13711def histogram(s):13712d = dict()13713for c in s:13714if c not in d:13715d[c] = 113716else:13717d[c] = d[c]+113718return d13719\end{verbatim}13720%13721This function also works for lists, tuples, and even dictionaries,13722as long as the elements of {\tt s} are hashable, so they can be used13723as keys in {\tt d}.1372413725\begin{verbatim}13726>>> t = ['spam', 'egg', 'spam', 'spam', 'bacon', 'spam']13727>>> histogram(t)13728{'bacon': 1, 'egg': 1, 'spam': 4}13729\end{verbatim}13730%13731Functions that work with several types are called {\bf polymorphic}.13732Polymorphism can facilitate code reuse. For example, the built-in13733function {\tt sum}, which adds the elements of a sequence, works13734as long as the elements of the sequence support addition.13735\index{polymorphism}1373613737Since Time objects provide an {\tt add} method, they work13738with {\tt sum}:1373913740\begin{verbatim}13741>>> t1 = Time(7, 43)13742>>> t2 = Time(7, 41)13743>>> t3 = Time(7, 37)13744>>> total = sum([t1, t2, t3])13745>>> print(total)1374623:01:0013747\end{verbatim}13748%13749In general, if all of the operations inside a function13750work with a given type, the function works with that type.1375113752The best kind of polymorphism is the unintentional kind, where13753you discover that a function you already wrote can be13754applied to a type you never planned for.137551375613757\section{Debugging}13758\index{debugging}1375913760It is legal to add attributes to objects at any point in the execution13761of a program, but if you have objects with the same type that don't13762have the same attributes, it is easy to make mistakes.13763It is considered a good idea to13764initialize all of an object's attributes in the init method.13765\index{init method}13766\index{attribute!initializing}1376713768If you are not sure whether an object has a particular attribute, you13769can use the built-in function {\tt hasattr} (see Section~\ref{hasattr}).13770\index{hasattr function}13771\index{function!hasattr}13772\index{dict attribute@\_\_dict\_\_ attribute}13773\index{attribute!\_\_dict\_\_}1377413775Another way to access attributes is the built-in function {\tt vars},13776which takes an object and returns a dictionary that maps from13777attribute names (as strings) to their values:1377813779\begin{verbatim}13780>>> p = Point(3, 4)13781>>> vars(p)13782{'y': 4, 'x': 3}13783\end{verbatim}13784%13785For purposes of debugging, you might find it useful to keep this13786function handy:1378713788\begin{verbatim}13789def print_attributes(obj):13790for attr in vars(obj):13791print(attr, getattr(obj, attr))13792\end{verbatim}13793%13794\verb"print_attributes" traverses the dictionary13795and prints each attribute name and its corresponding value.13796\index{traversal!dictionary}13797\index{dictionary!traversal}1379813799The built-in function {\tt getattr} takes an object and an attribute13800name (as a string) and returns the attribute's value.13801\index{getattr function}13802\index{function!getattr}138031380413805\section{Interface and implementation}1380613807One of the goals of object-oriented design is to make software more13808maintainable, which means that you can keep the program working when13809other parts of the system change, and modify the program to meet new13810requirements.13811\index{interface}13812\index{implementation}13813\index{maintainable}13814\index{object-oriented design}1381513816A design principle that helps achieve that goal is to keep13817interfaces separate from implementations. For objects, that means13818that the methods a class provides should not depend on how the13819attributes are represented.13820\index{attribute}1382113822For example, in this chapter we developed a class that represents13823a time of day. Methods provided by this class include13824\verb"time_to_int", \verb"is_after", and \verb"add_time".1382513826We could implement those methods in several ways. The details of the13827implementation depend on how we represent time. In this chapter, the13828attributes of a {\tt Time} object are {\tt hour}, {\tt minute}, and13829{\tt second}.1383013831As an alternative, we could replace these attributes with13832a single integer representing the number of seconds13833since midnight. This implementation would make some methods,13834like \verb"is_after", easier to write, but it makes other methods13835harder.1383613837After you deploy a new class, you might discover a better13838implementation. If other parts of the program are using your13839class, it might be time-consuming and error-prone to change the13840interface.1384113842But if you designed the interface carefully, you can13843change the implementation without changing the interface, which13844means that other parts of the program don't have to change.138451384613847\section{Glossary}1384813849\begin{description}1385013851\item[object-oriented language:] A language that provides features,13852such as programmer-defined types and methods, that facilitate13853object-oriented programming.13854\index{object-oriented language}1385513856\item[object-oriented programming:] A style of programming in which13857data and the operations that manipulate it are organized into classes13858and methods.13859\index{object-oriented programming}1386013861\item[method:] A function that is defined inside a class definition and13862is invoked on instances of that class.13863\index{method}1386413865\item[subject:] The object a method is invoked on.13866\index{subject}1386713868\item[positional argument:] An argument that does not include13869a parameter name, so it is not a keyword argument.13870\index{positional argument}13871\index{argument!positional}1387213873\item[operator overloading:] Changing the behavior of an operator like13874{\tt +} so it works with a programmer-defined type.13875\index{overloading}13876\index{operator!overloading}1387713878\item[type-based dispatch:] A programming pattern that checks the type13879of an operand and invokes different functions for different types.13880\index{type-based dispatch}1388113882\item[polymorphic:] Pertaining to a function that can work with more13883than one type.13884\index{polymorphism}1388513886\end{description}138871388813889\section{Exercises}1389013891\begin{exercise}1389213893Download the code from this chapter from13894\url{http://thinkpython2.com/code/Time2.py}. Change the attributes of13895{\tt Time} to be a single integer representing seconds since13896midnight. Then modify the methods (and the function13897\verb"int_to_time") to work with the new implementation. You13898should not have to modify the test code in {\tt main}. When you13899are done, the output should be the same as before. Solution:13900\url{http://thinkpython2.com/code/Time2_soln.py}.1390113902\end{exercise}139031390413905\begin{exercise}13906\label{kangaroo}13907\index{default value!avoiding mutable}13908\index{mutable object, as default value}13909\index{worst bug}13910\index{bug!worst}13911\index{Kangaroo class}13912\index{class!Kangaroo}1391313914This exercise is a cautionary tale about one of the most13915common, and difficult to find, errors in Python.13916Write a definition for a class named {\tt Kangaroo} with the following13917methods:1391813919\begin{enumerate}1392013921\item An \verb"__init__" method that initializes an attribute named13922\verb"pouch_contents" to an empty list.1392313924\item A method named \verb"put_in_pouch" that takes an object13925of any type and adds it to \verb"pouch_contents".1392613927\item A \verb"__str__" method that returns a string representation13928of the Kangaroo object and the contents of the pouch.1392913930\end{enumerate}13931%13932Test your code13933by creating two {\tt Kangaroo} objects, assigning them to variables13934named {\tt kanga} and {\tt roo}, and then adding {\tt roo} to the13935contents of {\tt kanga}'s pouch.1393613937Download \url{http://thinkpython2.com/code/BadKangaroo.py}. It contains13938a solution to the previous problem with one big, nasty bug.13939Find and fix the bug.1394013941If you get stuck, you can download13942\url{http://thinkpython2.com/code/GoodKangaroo.py}, which explains the13943problem and demonstrates a solution.13944\index{aliasing}13945\index{embedded object}13946\index{object!embedded}1394713948\end{exercise}13949139501395113952\chapter{Inheritance}1395313954The language feature most often associated with object-oriented13955programming is {\bf inheritance}. Inheritance is the ability to13956define a new class that is a modified version of an existing class.13957In this chapter I demonstrate inheritance using classes that represent13958playing cards, decks of cards, and poker hands.13959\index{deck}13960\index{card, playing}13961\index{poker}1396213963If you don't play13964poker, you can read about it at13965\url{http://en.wikipedia.org/wiki/Poker}, but you don't have to; I'll13966tell you what you need to know for the exercises.1396713968Code examples from13969this chapter are available from13970\url{http://thinkpython2.com/code/Card.py}.139711397213973\section{Card objects}1397413975There are fifty-two cards in a deck, each of which belongs to one of13976four suits and one of thirteen ranks. The suits are Spades, Hearts,13977Diamonds, and Clubs (in descending order in bridge). The ranks are13978Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King. Depending on13979the game that you are playing, an Ace may be higher than King13980or lower than 2.13981\index{rank}13982\index{suit}1398313984If we want to define a new object to represent a playing card, it is13985obvious what the attributes should be: {\tt rank} and13986{\tt suit}. It is not as obvious what type the attributes13987should be. One possibility is to use strings containing words like13988\verb"'Spade'" for suits and \verb"'Queen'" for ranks. One problem with13989this implementation is that it would not be easy to compare cards to13990see which had a higher rank or suit.13991\index{encode}13992\index{encrypt}13993\index{map to}13994\index{representation}1399513996An alternative is to use integers to {\bf encode} the ranks and suits.13997In this context, ``encode'' means that we are going to define a mapping13998between numbers and suits, or between numbers and ranks. This13999kind of encoding is not meant to be a secret (that14000would be ``encryption'').1400114002\newcommand{\mymapsto}{$\mapsto$}1400314004For example, this table shows the suits and the corresponding integer14005codes:1400614007\begin{tabular}{l c l}14008Spades & \mymapsto & 3 \\14009Hearts & \mymapsto & 2 \\14010Diamonds & \mymapsto & 1 \\14011Clubs & \mymapsto & 014012\end{tabular}1401314014This code makes it easy to compare cards; because higher suits map to14015higher numbers, we can compare suits by comparing their codes.1401614017The mapping for ranks is fairly obvious; each of the numerical ranks14018maps to the corresponding integer, and for face cards:1401914020\begin{tabular}{l c l}14021Jack & \mymapsto & 11 \\14022Queen & \mymapsto & 12 \\14023King & \mymapsto & 13 \\14024\end{tabular}1402514026I am using the \mymapsto~symbol to make it clear that these mappings14027are not part of the Python program. They are part of the program14028design, but they don't appear explicitly in the code.14029\index{Card class}14030\index{class!Card}1403114032The class definition for {\tt Card} looks like this:1403314034\begin{verbatim}14035class Card:14036"""Represents a standard playing card."""1403714038def __init__(self, suit=0, rank=2):14039self.suit = suit14040self.rank = rank14041\end{verbatim}14042%14043As usual, the init method takes an optional14044parameter for each attribute. The default card is14045the 2 of Clubs.14046\index{init method}14047\index{method!init}1404814049To create a Card, you call {\tt Card} with the14050suit and rank of the card you want.1405114052\begin{verbatim}14053queen_of_diamonds = Card(1, 12)14054\end{verbatim}14055%140561405714058\section{Class attributes}14059\label{class.attribute}14060\index{class attribute}14061\index{attribute!class}1406214063In order to print Card objects in a way that people can easily14064read, we need a mapping from the integer codes to the corresponding14065ranks and suits. A natural way to14066do that is with lists of strings. We assign these lists to {\bf class14067attributes}:1406814069\begin{verbatim}14070# inside class Card:1407114072suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']14073rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7',14074'8', '9', '10', 'Jack', 'Queen', 'King']1407514076def __str__(self):14077return '%s of %s' % (Card.rank_names[self.rank],14078Card.suit_names[self.suit])14079\end{verbatim}14080%14081Variables like \verb"suit_names" and \verb"rank_names", which are14082defined inside a class but outside of any method, are called14083class attributes because they are associated with the class object14084{\tt Card}.14085\index{instance attribute}14086\index{attribute!instance}1408714088This term distinguishes them from variables like {\tt suit} and {\tt14089rank}, which are called {\bf instance attributes} because they are14090associated with a particular instance.14091\index{dot notation}1409214093Both kinds of attribute are accessed using dot notation. For14094example, in \verb"__str__", {\tt self} is a Card object,14095and {\tt self.rank} is its rank. Similarly, {\tt Card}14096is a class object, and \verb"Card.rank_names" is a14097list of strings associated with the class.1409814099Every card has its own {\tt suit} and {\tt rank}, but there14100is only one copy of \verb"suit_names" and \verb"rank_names".1410114102Putting it all together, the expression14103\verb"Card.rank_names[self.rank]" means ``use the attribute {\tt rank}14104from the object {\tt self} as an index into the list \verb"rank_names"14105from the class {\tt Card}, and select the appropriate string.''1410614107The first element of \verb"rank_names" is {\tt None} because there14108is no card with rank zero. By including {\tt None} as a place-keeper,14109we get a mapping with the nice property that the index 2 maps to the14110string \verb"'2'", and so on. To avoid this tweak, we could have14111used a dictionary instead of a list.1411214113With the methods we have so far, we can create and print cards:1411414115\begin{verbatim}14116>>> card1 = Card(2, 11)14117>>> print(card1)14118Jack of Hearts14119\end{verbatim}1412014121\begin{figure}14122\centerline14123{\includegraphics[scale=0.8]{figs/card1.pdf}}14124\caption{Object diagram.}14125\label{fig.card1}14126\end{figure}1412714128Figure~\ref{fig.card1} is a diagram of the {\tt Card} class object and14129one Card instance. {\tt Card} is a class object; its type is {\tt14130type}. {\tt card1} is an instance of {\tt Card}, so its type is14131{\tt Card}. To save space, I didn't draw the contents of14132\verb"suit_names" and \verb"rank_names". \index{state diagram}14133\index{diagram!state} \index{object diagram} \index{diagram!object}141341413514136\section{Comparing cards}14137\label{comparecard}14138\index{operator!relational}14139\index{relational operator}1414014141For built-in types, there are relational operators14142({\tt <}, {\tt >}, {\tt ==}, etc.)14143that compare14144values and determine when one is greater than, less than, or equal to14145another. For programmer-defined types, we can override the behavior of14146the built-in operators by providing a method named14147\verb"__lt__", which stands for ``less than''.14148\index{programmer-defined type}14149\index{type!programmer-defined}1415014151\verb"__lt__" takes two parameters, {\tt self} and {\tt other},14152and returns {\tt True} if {\tt self} is strictly less than {\tt other}.14153\index{override}14154\index{operator overloading}1415514156The correct ordering for cards is not obvious.14157For example, which14158is better, the 3 of Clubs or the 2 of Diamonds? One has a higher14159rank, but the other has a higher suit. In order to compare14160cards, you have to decide whether rank or suit is more important.1416114162The answer might depend on what game you are playing, but to keep14163things simple, we'll make the arbitrary choice that suit is more14164important, so all of the Spades outrank all of the Diamonds,14165and so on.14166\index{cmp method@\_\_cmp\_\_ method}14167\index{method!\_\_cmp\_\_}1416814169With that decided, we can write \verb"__lt__":1417014171\begin{verbatim}14172# inside class Card:1417314174def __lt__(self, other):14175# check the suits14176if self.suit < other.suit: return True14177if self.suit > other.suit: return False1417814179# suits are the same... check ranks14180return self.rank < other.rank14181\end{verbatim}14182%14183You can write this more concisely using tuple comparison:14184\index{tuple!comparison}14185\index{comparison!tuple}1418614187\begin{verbatim}14188# inside class Card:1418914190def __lt__(self, other):14191t1 = self.suit, self.rank14192t2 = other.suit, other.rank14193return t1 < t214194\end{verbatim}14195%14196As an exercise, write an \verb"__lt__" method for Time objects. You14197can use tuple comparison, but you also might consider14198comparing integers.141991420014201\section{Decks}14202\index{list!of objects}14203\index{deck, playing cards}1420414205Now that we have Cards, the next step is to define Decks. Since a14206deck is made up of cards, it is natural for each Deck to contain a14207list of cards as an attribute.14208\index{init method}14209\index{method!init}1421014211The following is a class definition for {\tt Deck}. The14212init method creates the attribute {\tt cards} and generates14213the standard set of fifty-two cards:14214\index{composition}14215\index{loop!nested}14216\index{Deck class}14217\index{class!Deck}1421814219\begin{verbatim}14220class Deck:1422114222def __init__(self):14223self.cards = []14224for suit in range(4):14225for rank in range(1, 14):14226card = Card(suit, rank)14227self.cards.append(card)14228\end{verbatim}14229%14230The easiest way to populate the deck is with a nested loop. The outer14231loop enumerates the suits from 0 to 3. The inner loop enumerates the14232ranks from 1 to 13. Each iteration14233creates a new Card with the current suit and rank,14234and appends it to {\tt self.cards}.14235\index{append method}14236\index{method!append}142371423814239\section{Printing the deck}14240\label{printdeck}14241\index{str method@\_\_str\_\_ method}14242\index{method!\_\_str\_\_}1424314244Here is a \verb"__str__" method for {\tt Deck}:1424514246\begin{verbatim}14247#inside class Deck:1424814249def __str__(self):14250res = []14251for card in self.cards:14252res.append(str(card))14253return '\n'.join(res)14254\end{verbatim}14255%14256This method demonstrates an efficient way to accumulate a large14257string: building a list of strings and then using the string method14258{\tt join}. The built-in function {\tt str} invokes the14259\verb"__str__" method on each card and returns the string14260representation. \index{accumulator!string} \index{string!accumulator}14261\index{join method} \index{method!join} \index{newline}1426214263Since we invoke {\tt join} on a newline character, the cards14264are separated by newlines. Here's what the result looks like:1426514266\begin{verbatim}14267>>> deck = Deck()14268>>> print(deck)14269Ace of Clubs142702 of Clubs142713 of Clubs14272...1427310 of Spades14274Jack of Spades14275Queen of Spades14276King of Spades14277\end{verbatim}14278%14279Even though the result appears on 52 lines, it is14280one long string that contains newlines.142811428214283\section{Add, remove, shuffle and sort}1428414285To deal cards, we would like a method that14286removes a card from the deck and returns it.14287The list method {\tt pop} provides a convenient way to do that:14288\index{pop method}14289\index{method!pop}1429014291\begin{verbatim}14292#inside class Deck:1429314294def pop_card(self):14295return self.cards.pop()14296\end{verbatim}14297%14298Since {\tt pop} removes the {\em last} card in the list, we are14299dealing from the bottom of the deck.14300\index{append method}14301\index{method!append}1430214303To add a card, we can use the list method {\tt append}:1430414305\begin{verbatim}14306#inside class Deck:1430714308def add_card(self, card):14309self.cards.append(card)14310\end{verbatim}14311%14312A method like this that uses another method without doing14313much work is sometimes called a {\bf veneer}. The metaphor14314comes from woodworking, where a veneer is a thin14315layer of good quality wood glued to the surface of a cheaper piece of14316wood to improve the appearance.14317\index{veneer}1431814319In this case \verb"add_card" is a ``thin'' method that expresses14320a list operation in terms appropriate for decks. It14321improves the appearance, or interface, of the14322implementation.1432314324As another example, we can write a Deck method named {\tt shuffle}14325using the function {\tt shuffle} from the {\tt random} module:14326\index{random module}14327\index{module!random}14328\index{shuffle function}14329\index{function!shuffle}1433014331\begin{verbatim}14332# inside class Deck:1433314334def shuffle(self):14335random.shuffle(self.cards)14336\end{verbatim}14337%14338Don't forget to import {\tt random}.1433914340As an exercise, write a Deck method named {\tt sort} that uses the14341list method {\tt sort} to sort the cards in a {\tt Deck}. {\tt sort}14342uses the \verb"__lt__" method we defined to determine the order.14343\index{sort method} \index{method!sort}14344143451434614347\section{Inheritance}14348\index{inheritance}14349\index{object-oriented programming}1435014351Inheritance is the ability to define a new class that is a modified14352version of an existing class. As an example, let's say we want a14353class to represent a ``hand'', that is, the cards held by one player.14354A hand is similar to a deck: both are made up of a collection of14355cards, and both require operations like adding and removing cards.1435614357A hand is also different from a deck; there are operations we want for14358hands that don't make sense for a deck. For example, in poker we14359might compare two hands to see which one wins. In bridge, we might14360compute a score for a hand in order to make a bid.1436114362This relationship between classes---similar, but different---lends14363itself to inheritance.14364To define a new class that inherits from an existing class,14365you put the name of the existing class in parentheses:14366\index{parentheses!parent class in}14367\index{parent class}14368\index{class!parent}14369\index{Hand class}14370\index{class!Hand}1437114372\begin{verbatim}14373class Hand(Deck):14374"""Represents a hand of playing cards."""14375\end{verbatim}14376%14377This definition indicates that {\tt Hand} inherits from {\tt Deck};14378that means we can use methods like \verb"pop_card" and \verb"add_card"14379for Hands as well as Decks.1438014381When a new class inherits from an existing one, the existing14382one is called the {\bf parent} and the new class is14383called the {\bf child}.14384\index{parent class}14385\index{child class}14386\index{class!child}1438714388In this example, {\tt Hand} inherits \verb"__init__" from {\tt Deck},14389but it doesn't really do what we want: instead of populating the hand14390with 52 new cards, the init method for Hands should initialize {\tt14391cards} with an empty list. \index{override} \index{init method}14392\index{method!init}1439314394If we provide an init method in the {\tt Hand} class, it overrides the14395one in the {\tt Deck} class:1439614397\begin{verbatim}14398# inside class Hand:1439914400def __init__(self, label=''):14401self.cards = []14402self.label = label14403\end{verbatim}14404%14405When you create a Hand, Python invokes this init method, not the14406one in {\tt Deck}.1440714408\begin{verbatim}14409>>> hand = Hand('new hand')14410>>> hand.cards14411[]14412>>> hand.label14413'new hand'14414\end{verbatim}14415%14416The other methods are inherited from {\tt Deck}, so we can use14417\verb"pop_card" and \verb"add_card" to deal a card:1441814419\begin{verbatim}14420>>> deck = Deck()14421>>> card = deck.pop_card()14422>>> hand.add_card(card)14423>>> print(hand)14424King of Spades14425\end{verbatim}14426%14427A natural next step is to encapsulate this code in a method14428called \verb"move_cards":14429\index{encapsulation}1443014431\begin{verbatim}14432#inside class Deck:1443314434def move_cards(self, hand, num):14435for i in range(num):14436hand.add_card(self.pop_card())14437\end{verbatim}14438%14439\verb"move_cards" takes two arguments, a Hand object and the number of14440cards to deal. It modifies both {\tt self} and {\tt hand}, and14441returns {\tt None}.1444214443In some games, cards are moved from one hand to another,14444or from a hand back to the deck. You can use \verb"move_cards"14445for any of these operations: {\tt self} can be either a Deck14446or a Hand, and {\tt hand}, despite the name, can also be a {\tt Deck}.1444714448Inheritance is a useful feature. Some programs that would be14449repetitive without inheritance can be written more elegantly14450with it. Inheritance can facilitate code reuse, since you can14451customize the behavior of parent classes without having to modify14452them. In some cases, the inheritance structure reflects the natural14453structure of the problem, which makes the design easier to14454understand.1445514456On the other hand, inheritance can make programs difficult to read.14457When a method is invoked, it is sometimes not clear where to find its14458definition. The relevant code may be spread across several modules.14459Also, many of the things that can be done using inheritance can be14460done as well or better without it.144611446214463\section{Class diagrams}14464\label{class.diagram}1446514466So far we have seen stack diagrams, which show the state of14467a program, and object diagrams, which show the attributes14468of an object and their values. These diagrams represent a snapshot14469in the execution of a program, so they change as the program14470runs.1447114472They are also highly detailed; for some purposes, too14473detailed. A class diagram is a more abstract representation14474of the structure of a program. Instead of showing individual14475objects, it shows classes and the relationships between them.1447614477There are several kinds of relationship between classes:1447814479\begin{itemize}1448014481\item Objects in one class might contain references to objects14482in another class. For example, each Rectangle contains a reference14483to a Point, and each Deck contains references to many Cards.14484This kind of relationship is called {\bf HAS-A}, as in, ``a Rectangle14485has a Point.''1448614487\item One class might inherit from another. This relationship14488is called {\bf IS-A}, as in, ``a Hand is a kind of a Deck.''1448914490\item One class might depend on another in the sense that objects14491in one class take objects in the second class as parameters, or14492use objects in the second class as part of a computation. This14493kind of relationship is called a {\bf dependency}.1449414495\end{itemize}14496\index{IS-A relationship}14497\index{HAS-A relationship}14498\index{class diagram}14499\index{diagram!class}1450014501A {\bf class diagram} is a graphical representation of these14502relationships. For example, Figure~\ref{fig.class1} shows the14503relationships between {\tt Card}, {\tt Deck} and {\tt Hand}.1450414505\begin{figure}14506\centerline14507{\includegraphics[scale=0.8]{figs/class1.pdf}}14508\caption{Class diagram.}14509\label{fig.class1}14510\end{figure}1451114512The arrow with a hollow triangle head represents an IS-A14513relationship; in this case it indicates that Hand inherits14514from Deck.1451514516The standard arrow head represents a HAS-A14517relationship; in this case a Deck has references to Card14518objects.14519\index{multiplicity (in class diagram)}1452014521The star ({\tt *}) near the arrow head is a14522{\bf multiplicity}; it indicates how many Cards a Deck has.14523A multiplicity can be a simple number, like {\tt 52}, a range,14524like {\tt 5..7} or a star, which indicates that a Deck can14525have any number of Cards.1452614527There are no dependencies in this diagram. They would normally14528be shown with a dashed arrow. Or if there are a lot of14529dependencies, they are sometimes omitted.1453014531A more detailed diagram might show that a Deck actually14532contains a {\em list} of Cards, but built-in types14533like list and dict are usually not included in class diagrams.145341453514536\section{Debugging}14537\index{debugging}1453814539Inheritance can make debugging difficult because when you invoke a14540method on an object, it might be hard to figure out which method will14541be invoked.14542\index{inheritance}1454314544Suppose you are writing a function that works with Hand objects.14545You would like it to work with all kinds of Hands, like14546PokerHands, BridgeHands, etc. If you invoke a method like14547{\tt shuffle}, you might get the one defined in {\tt Deck},14548but if any of the subclasses override this method, you'll14549get that version instead. This behavior is usually a good14550thing, but it can be confusing.1455114552Any time you are unsure about the flow of execution through your14553program, the simplest solution is to add print statements at the14554beginning of the relevant methods. If {\tt Deck.shuffle} prints a14555message that says something like {\tt Running Deck.shuffle}, then as14556the program runs it traces the flow of execution.14557\index{flow of execution}1455814559As an alternative, you could use this function, which takes an14560object and a method name (as a string) and returns the class that14561provides the definition of the method:1456214563\begin{verbatim}14564def find_defining_class(obj, meth_name):14565for ty in type(obj).mro():14566if meth_name in ty.__dict__:14567return ty14568\end{verbatim}14569%14570Here's an example:1457114572\begin{verbatim}14573>>> hand = Hand()14574>>> find_defining_class(hand, 'shuffle')14575<class '__main__.Deck'>14576\end{verbatim}14577%14578So the {\tt shuffle} method for this Hand is the one in {\tt Deck}.14579\index{mro method}14580\index{method!mro}14581\index{method resolution order}1458214583\verb"find_defining_class" uses the {\tt mro} method to get the list14584of class objects (types) that will be searched for methods. ``MRO''14585stands for ``method resolution order'', which is the sequence of14586classes Python searches to ``resolve'' a method name.1458714588Here's a design suggestion: when you override a method,14589the interface of the new method should be the same as the old. It14590should take the same parameters, return the same type, and obey the14591same preconditions and postconditions. If you follow this rule, you14592will find that any function designed to work with an instance of a14593parent class, like a Deck, will also work with instances of child14594classes like a Hand and PokerHand.14595\index{override}14596\index{interface}14597\index{precondition}14598\index{postcondition}1459914600If you violate this rule, which is called the ``Liskov substitution14601principle'', your code will collapse like (sorry) a house of cards.14602\index{Liskov substitution principle}146031460414605\section{Data encapsulation}1460614607The previous chapters demonstrate a development plan we might call14608``object-oriented design''. We identified objects we needed---like14609{\tt Point}, {\tt Rectangle} and {\tt Time}---and defined classes to14610represent them. In each case there is an obvious correspondence14611between the object and some entity in the real world (or at least a14612mathematical world).14613\index{development plan!data encapsulation}1461414615But sometimes it is less obvious what objects you need14616and how they should interact. In that case you need a different14617development plan. In the same way that we discovered function14618interfaces by encapsulation and generalization, we can discover14619class interfaces by {\bf data encapsulation}.14620\index{data encapsulation}1462114622Markov analysis, from Section~\ref{markov}, provides a good example.14623If you download my code from \url{http://thinkpython2.com/code/markov.py},14624you'll see that it uses two global variables---\verb"suffix_map" and14625\verb"prefix"---that are read and written from several functions.1462614627\begin{verbatim}14628suffix_map = {}14629prefix = ()14630\end{verbatim}1463114632Because these variables are global, we can only run one analysis at a14633time. If we read two texts, their prefixes and suffixes would be14634added to the same data structures (which makes for some interesting14635generated text).1463614637To run multiple analyses, and keep them separate, we can encapsulate14638the state of each analysis in an object.14639Here's what that looks like:1464014641\begin{verbatim}14642class Markov:1464314644def __init__(self):14645self.suffix_map = {}14646self.prefix = ()14647\end{verbatim}1464814649Next, we transform the functions into methods. For example,14650here's \verb"process_word":1465114652\begin{verbatim}14653def process_word(self, word, order=2):14654if len(self.prefix) < order:14655self.prefix += (word,)14656return1465714658try:14659self.suffix_map[self.prefix].append(word)14660except KeyError:14661# if there is no entry for this prefix, make one14662self.suffix_map[self.prefix] = [word]1466314664self.prefix = shift(self.prefix, word)14665\end{verbatim}1466614667Transforming a program like this---changing the design without14668changing the behavior---is another example of refactoring14669(see Section~\ref{refactoring}).14670\index{refactoring}1467114672This example suggests a development plan for designing objects and14673methods:1467414675\begin{enumerate}1467614677\item Start by writing functions that read and write global14678variables (when necessary).1467914680\item Once you get the program working, look for associations14681between global variables and the functions that use them.1468214683\item Encapsulate related variables as attributes of an object.1468414685\item Transform the associated functions into methods of the new14686class.1468714688\end{enumerate}1468914690As an exercise, download my Markov code from14691\url{http://thinkpython2.com/code/markov.py}, and follow the steps14692described above to encapsulate the global variables as attributes of a14693new class called {\tt Markov}. Solution:14694\url{http://thinkpython2.com/code/markov2.py}.146951469614697\section{Glossary}1469814699\begin{description}1470014701\item[encode:] To represent one set of values using another14702set of values by constructing a mapping between them.14703\index{encode}1470414705\item[class attribute:] An attribute associated with a class14706object. Class attributes are defined inside14707a class definition but outside any method.14708\index{class attribute}14709\index{attribute!class}1471014711\item[instance attribute:] An attribute associated with an14712instance of a class.14713\index{instance attribute}14714\index{attribute!instance}1471514716\item[veneer:] A method or function that provides a different14717interface to another function without doing much computation.14718\index{veneer}1471914720\item[inheritance:] The ability to define a new class that is a14721modified version of a previously defined class.14722\index{inheritance}1472314724\item[parent class:] The class from which a child class inherits.14725\index{parent class}1472614727\item[child class:] A new class created by inheriting from an14728existing class; also called a ``subclass''.14729\index{child class}14730\index{class!child}1473114732\item[IS-A relationship:] A relationship between a child class14733and its parent class.14734\index{IS-A relationship}1473514736\item[HAS-A relationship:] A relationship between two classes14737where instances of one class contain references to instances of14738the other.14739\index{HAS-A relationship}1474014741\item[dependency:] A relationship between two classes14742where instances of one class use instances of the other class,14743but do not store them as attributes.14744\index{HAS-A relationship}1474514746\item[class diagram:] A diagram that shows the classes in a program14747and the relationships between them.14748\index{class diagram}14749\index{diagram!class}1475014751\item[multiplicity:] A notation in a class diagram that shows, for14752a HAS-A relationship, how many references there are to instances14753of another class.14754\index{multiplicity (in class diagram)}1475514756\item[data encapsulation:] A program development plan that14757involves a prototype using global variables and a final version14758that makes the global variables into instance attributes.14759\index{data encapsulation}14760\index{development plan!data encapsulation}1476114762\end{description}147631476414765\section{Exercises}1476614767\begin{exercise}14768For the following program, draw a UML class diagram that shows14769these classes and the relationships among them.1477014771\begin{verbatim}14772class PingPongParent:14773pass1477414775class Ping(PingPongParent):14776def __init__(self, pong):14777self.pong = pong147781477914780class Pong(PingPongParent):14781def __init__(self, pings=None):14782if pings is None:14783self.pings = []14784else:14785self.pings = pings1478614787def add_ping(self, ping):14788self.pings.append(ping)1478914790pong = Pong()14791ping = Ping(pong)14792pong.add_ping(ping)14793\end{verbatim}147941479514796\end{exercise}14797147981479914800\begin{exercise}14801Write a Deck method called \verb"deal_hands" that14802takes two parameters, the number of hands and the number of cards per14803hand. It should create the appropriate number of Hand objects, deal14804the appropriate number of cards per hand, and return a list of Hands.14805\end{exercise}148061480714808\begin{exercise}14809\label{poker}1481014811The following are the possible hands in poker, in increasing order14812of value and decreasing order of probability:14813\index{poker}1481414815\begin{description}1481614817\item[pair:] two cards with the same rank14818\vspace{-0.05in}1481914820\item[two pair:] two pairs of cards with the same rank14821\vspace{-0.05in}1482214823\item[three of a kind:] three cards with the same rank14824\vspace{-0.05in}1482514826\item[straight:] five cards with ranks in sequence (aces can14827be high or low, so {\tt Ace-2-3-4-5} is a straight and so is {\tt1482810-Jack-Queen-King-Ace}, but {\tt Queen-King-Ace-2-3} is not.)14829\vspace{-0.05in}1483014831\item[flush:] five cards with the same suit14832\vspace{-0.05in}1483314834\item[full house:] three cards with one rank, two cards with another14835\vspace{-0.05in}1483614837\item[four of a kind:] four cards with the same rank14838\vspace{-0.05in}1483914840\item[straight flush:] five cards in sequence (as defined above) and14841with the same suit14842\vspace{-0.05in}1484314844\end{description}14845%14846The goal of these exercises is to estimate14847the probability of drawing these various hands.1484814849\begin{enumerate}1485014851\item Download the following files from \url{http://thinkpython2.com/code}:1485214853\begin{description}1485414855\item[{\tt Card.py}]: A complete version of the {\tt Card},14856{\tt Deck} and {\tt Hand} classes in this chapter.1485714858\item[{\tt PokerHand.py}]: An incomplete implementation of a class14859that represents a poker hand, and some code that tests it.1486014861\end{description}14862%14863\item If you run {\tt PokerHand.py}, it deals seven 7-card poker hands14864and checks to see if any of them contains a flush. Read this14865code carefully before you go on.1486614867\item Add methods to {\tt PokerHand.py} named \verb"has_pair",14868\verb"has_twopair", etc. that return True or False according to14869whether or not the hand meets the relevant criteria. Your code should14870work correctly for ``hands'' that contain any number of cards14871(although 5 and 7 are the most common sizes).1487214873\item Write a method named {\tt classify} that figures out14874the highest-value classification for a hand and sets the14875{\tt label} attribute accordingly. For example, a 7-card hand14876might contain a flush and a pair; it should be labeled ``flush''.1487714878\item When you are convinced that your classification methods are14879working, the next step is to estimate the probabilities of the various14880hands. Write a function in {\tt PokerHand.py} that shuffles a deck of14881cards, divides it into hands, classifies the hands, and counts the14882number of times various classifications appear.1488314884\item Print a table of the classifications and their probabilities.14885Run your program with larger and larger numbers of hands until the14886output values converge to a reasonable degree of accuracy. Compare14887your results to the values at \url{http://en.wikipedia.org/wiki/Hand_rankings}.1488814889\end{enumerate}1489014891Solution: \url{http://thinkpython2.com/code/PokerHandSoln.py}.14892\end{exercise}148931489414895\chapter{The Goodies}1489614897One of my goals for this book has been to teach you as little Python14898as possible. When there were two ways to do something, I picked14899one and avoided mentioning the other. Or sometimes I put the second14900one into an exercise.1490114902Now I want to go back for some of the good bits that got left behind.14903Python provides a number of features that are not really necessary---you14904can write good code without them---but with them you can sometimes14905write code that's more concise, readable or efficient, and sometimes14906all three.1490714908% TODO: add the with statement1490914910\section{Conditional expressions}1491114912We saw conditional statements in Section~\ref{conditional.execution}.14913Conditional statements are often used to choose one of two values;14914for example:14915\index{conditional expression}14916\index{expression!conditional}1491714918\begin{verbatim}14919if x > 0:14920y = math.log(x)14921else:14922y = float('nan')14923\end{verbatim}1492414925This statement checks whether {\tt x} is positive. If so, it computes14926{\tt math.log}. If not, {\tt math.log} would raise a ValueError. To14927avoid stopping the program, we generate a ``NaN'', which is a special14928floating-point value that represents ``Not a Number''.14929\index{NaN}14930\index{floating-point}1493114932We can write this statement more concisely using a {\bf conditional14933expression}:1493414935\begin{verbatim}14936y = math.log(x) if x > 0 else float('nan')14937\end{verbatim}1493814939You can almost read this line like English: ``{\tt y} gets log-{\tt x}14940if {\tt x} is greater than 0; otherwise it gets NaN''.1494114942Recursive functions can sometimes be rewritten using conditional14943expressions. For example, here is a recursive version of {\tt factorial}:14944\index{factorial}14945\index{function!factorial}1494614947\begin{verbatim}14948def factorial(n):14949if n == 0:14950return 114951else:14952return n * factorial(n-1)14953\end{verbatim}1495414955We can rewrite it like this:1495614957\begin{verbatim}14958def factorial(n):14959return 1 if n == 0 else n * factorial(n-1)14960\end{verbatim}1496114962Another use of conditional expressions is handling optional14963arguments. For example, here is the init method from14964{\tt GoodKangaroo} (see Exercise~\ref{kangaroo}):14965\index{optional argument}14966\index{argument!optional}1496714968\begin{verbatim}14969def __init__(self, name, contents=None):14970self.name = name14971if contents == None:14972contents = []14973self.pouch_contents = contents14974\end{verbatim}1497514976We can rewrite this one like this:1497714978\begin{verbatim}14979def __init__(self, name, contents=None):14980self.name = name14981self.pouch_contents = [] if contents == None else contents14982\end{verbatim}1498314984In general, you can replace a conditional statement with a conditional14985expression if both branches contain simple expressions that are14986either returned or assigned to the same variable.14987\index{conditional statement}14988\index{statement!conditional}14989149901499114992\section{List comprehensions}1499314994In Section~\ref{filter} we saw the map and filter patterns. For14995example, this function takes a list of strings, maps the string method14996{\tt capitalize} to the elements, and returns a new list of strings:1499714998\begin{verbatim}14999def capitalize_all(t):15000res = []15001for s in t:15002res.append(s.capitalize())15003return res15004\end{verbatim}1500515006We can write this more concisely using a {\bf list comprehension}:15007\index{list comprehension}1500815009\begin{verbatim}15010def capitalize_all(t):15011return [s.capitalize() for s in t]15012\end{verbatim}1501315014The bracket operators indicate that we are constructing a new15015list. The expression inside the brackets specifies the elements15016of the list, and the {\tt for} clause indicates what sequence15017we are traversing.15018\index{list}15019\index{for loop}1502015021The syntax of a list comprehension is a little awkward because15022the loop variable, {\tt s} in this example, appears in the expression15023before we get to the definition.15024\index{loop variable}1502515026List comprehensions can also be used for filtering. For example,15027this function selects only the elements of {\tt t} that are15028upper case, and returns a new list:15029\index{filter pattern}15030\index{pattern!filter}1503115032\begin{verbatim}15033def only_upper(t):15034res = []15035for s in t:15036if s.isupper():15037res.append(s)15038return res15039\end{verbatim}1504015041We can rewrite it using a list comprehension1504215043\begin{verbatim}15044def only_upper(t):15045return [s for s in t if s.isupper()]15046\end{verbatim}1504715048List comprehensions are concise and easy to read, at least for simple15049expressions. And they are usually faster than the equivalent for15050loops, sometimes much faster. So if you are mad at me for not15051mentioning them earlier, I understand.1505215053But, in my defense, list comprehensions are harder to debug because15054you can't put a print statement inside the loop. I suggest that you15055use them only if the computation is simple enough that you are likely15056to get it right the first time. And for beginners that means never.15057\index{debugging}15058150591506015061\section{Generator expressions}1506215063{\bf Generator expressions} are similar to list comprehensions, but15064with parentheses instead of square brackets:15065\index{generator expression}15066\index{expression!generator}1506715068\begin{verbatim}15069>>> g = (x**2 for x in range(5))15070>>> g15071<generator object <genexpr> at 0x7f4c45a786c0>15072\end{verbatim}15073%15074The result is a generator object that knows how to iterate through15075a sequence of values. But unlike a list comprehension, it does not15076compute the values all at once; it waits to be asked. The built-in15077function {\tt next} gets the next value from the generator:15078\index{generator object}15079\index{object!generator}1508015081\begin{verbatim}15082>>> next(g)15083015084>>> next(g)15085115086\end{verbatim}15087%15088When you get to the end of the sequence, {\tt next} raises a15089StopIteration exception. You can also use a {\tt for} loop to iterate15090through the values:15091\index{StopIteration}15092\index{exception!StopIteration}1509315094\begin{verbatim}15095>>> for val in g:15096... print(val)150974150989150991615100\end{verbatim}15101%15102The generator object keeps track of where it is in the sequence,15103so the {\tt for} loop picks up where {\tt next} left off. Once the15104generator is exhausted, it continues to raise {\tt StopIteration}:1510515106\begin{verbatim}15107>>> next(g)15108StopIteration15109\end{verbatim}1511015111Generator expressions are often used with functions like {\tt sum},15112{\tt max}, and {\tt min}:15113\index{sum}15114\index{function!sum}1511515116\begin{verbatim}15117>>> sum(x**2 for x in range(5))151183015119\end{verbatim}151201512115122\section{{\tt any} and {\tt all}}1512315124Python provides a built-in function, {\tt any}, that takes a sequence15125of boolean values and returns {\tt True} if any of the values are {\tt15126True}. It works on lists:15127\index{any}15128\index{built-in function!any}1512915130\begin{verbatim}15131>>> any([False, False, True])15132True15133\end{verbatim}15134%15135But it is often used with generator expressions:15136\index{generator expression}15137\index{expression!generator}1513815139\begin{verbatim}15140>>> any(letter == 't' for letter in 'monty')15141True15142\end{verbatim}15143%15144That example isn't very useful because it does the same thing15145as the {\tt in} operator. But we could use {\tt any} to rewrite15146some of the search functions we wrote in Section~\ref{search}. For15147example, we could write {\tt avoids} like this:15148\index{search pattern}15149\index{pattern!search}1515015151\begin{verbatim}15152def avoids(word, forbidden):15153return not any(letter in forbidden for letter in word)15154\end{verbatim}15155%15156The function almost reads like English, ``{\tt word} avoids15157{\tt forbidden} if there are not any forbidden letters in {\tt word}.''1515815159Using {\tt any} with a generator expression is efficient because15160it stops immediately if it finds a {\tt True} value,15161so it doesn't have to evaluate the whole sequence.1516215163Python provides another built-in function, {\tt all}, that returns15164{\tt True} if every element of the sequence is {\tt True}. As15165an exercise, use {\tt all} to re-write \verb"uses_all" from15166Section~\ref{search}.15167\index{all}15168\index{built-in function!any}151691517015171\section{Sets}15172\label{sets}1517315174In Section~\ref{dictsub} I use dictionaries to find the words15175that appear in a document but not in a word list. The function15176I wrote takes {\tt d1}, which contains the words from the document15177as keys, and {\tt d2}, which contains the list of words. It15178returns a dictionary that contains the keys from {\tt d1} that15179are not in {\tt d2}.1518015181\begin{verbatim}15182def subtract(d1, d2):15183res = dict()15184for key in d1:15185if key not in d2:15186res[key] = None15187return res15188\end{verbatim}15189%15190In all of these dictionaries, the values are {\tt None} because15191we never use them. As a result, we waste some storage space.15192\index{dictionary subtraction}1519315194Python provides another built-in type, called a {\tt set}, that15195behaves like a collection of dictionary keys with no values. Adding15196elements to a set is fast; so is checking membership. And sets15197provide methods and operators to compute common set operations.15198\index{set}15199\index{object!set}1520015201For example, set subtraction is available as a method called15202{\tt difference} or as an operator, {\tt -}. So we can rewrite15203{\tt subtract} like this:15204\index{set subtraction}1520515206\begin{verbatim}15207def subtract(d1, d2):15208return set(d1) - set(d2)15209\end{verbatim}15210%15211The result is a set instead of a dictionary, but for operations like15212iteration, the behavior is the same.1521315214Some of the exercises in this book can be done concisely and15215efficiently with sets. For example, here is a solution to15216\verb"has_duplicates", from15217Exercise~\ref{duplicate}, that uses a dictionary:1521815219\begin{verbatim}15220def has_duplicates(t):15221d = {}15222for x in t:15223if x in d:15224return True15225d[x] = True15226return False15227\end{verbatim}1522815229When an element appears for the first time, it is added to the15230dictionary. If the same element appears again, the function returns15231{\tt True}.1523215233Using sets, we can write the same function like this:1523415235\begin{verbatim}15236def has_duplicates(t):15237return len(set(t)) < len(t)15238\end{verbatim}15239%15240An element can only appear in a set once, so if an element in {\tt t}15241appears more than once, the set will be smaller than {\tt t}. If there15242are no duplicates, the set will be the same size as {\tt t}.15243\index{duplicate}1524415245We can also use sets to do some of the exercises in15246Chapter~\ref{wordplay}. For example, here's a version of15247\verb"uses_only" with a loop:1524815249\begin{verbatim}15250def uses_only(word, available):15251for letter in word:15252if letter not in available:15253return False15254return True15255\end{verbatim}15256%15257\verb"uses_only" checks whether all letters in {\tt word} are15258in {\tt available}. We can rewrite it like this:1525915260\begin{verbatim}15261def uses_only(word, available):15262return set(word) <= set(available)15263\end{verbatim}15264%15265The \verb"<=" operator checks whether one set is a subset of another,15266including the possibility that they are equal, which is true if all15267the letters in {\tt word} appear in {\tt available}.15268\index{subset}1526915270As an exercise, rewrite \verb"avoids" using sets.152711527215273\section{Counters}1527415275A Counter is like a set, except that if an element appears more15276than once, the Counter keeps track of how many times it appears.15277If you are familiar with the mathematical idea of a {\bf multiset},15278a Counter is a natural way to represent a multiset.15279\index{Counter}15280\index{object!Counter}15281\index{multiset}1528215283Counter is defined in a standard module called {\tt collections},15284so you have to import it. You can initialize a Counter with a string,15285list, or anything else that supports iteration:15286\index{collections}15287\index{module!collections}1528815289\begin{verbatim}15290>>> from collections import Counter15291>>> count = Counter('parrot')15292>>> count15293Counter({'r': 2, 't': 1, 'o': 1, 'p': 1, 'a': 1})15294\end{verbatim}1529515296Counters behave like dictionaries in many ways; they map from each15297key to the number of times it appears. As in dictionaries,15298the keys have to be hashable.1529915300Unlike dictionaries, Counters don't raise an exception if you access15301an element that doesn't appear. Instead, they return 0:1530215303\begin{verbatim}15304>>> count['d']15305015306\end{verbatim}1530715308We can use Counters to rewrite \verb"is_anagram" from15309Exercise~\ref{anagram}:1531015311\begin{verbatim}15312def is_anagram(word1, word2):15313return Counter(word1) == Counter(word2)15314\end{verbatim}1531515316If two words are anagrams, they contain the same letters with the same15317counts, so their Counters are equivalent.1531815319Counters provide methods and operators to perform set-like operations,15320including addition, subtraction, union and intersection. And15321they provide an often-useful method, \verb"most_common", which15322returns a list of value-frequency pairs, sorted from most common to15323least:1532415325\begin{verbatim}15326>>> count = Counter('parrot')15327>>> for val, freq in count.most_common(3):15328... print(val, freq)15329r 215330p 115331a 115332\end{verbatim}153331533415335\section{defaultdict}1533615337The {\tt collections} module also provides {\tt defaultdict}, which is15338like a dictionary except that if you access a key that doesn't exist,15339it can generate a new value on the fly.15340\index{defaultdict}15341\index{object!defaultdict}15342\index{collections}15343\index{module!collections}1534415345When you create a defaultdict, you provide a function that's used to15346create new values. A function used to create objects is sometimes15347called a {\bf factory}. The built-in functions that create lists, sets,15348and other types can be used as factories:15349\index{factory function}1535015351\begin{verbatim}15352>>> from collections import defaultdict15353>>> d = defaultdict(list)15354\end{verbatim}1535515356Notice that the argument is {\tt list}, which is a class object,15357not {\tt list()}, which is a new list. The function you provide15358doesn't get called unless you access a key that doesn't exist.1535915360\begin{verbatim}15361>>> t = d['new key']15362>>> t15363[]15364\end{verbatim}1536515366The new list, which we're calling {\tt t}, is also added to the15367dictionary. So if we modify {\tt t}, the change appears in {\tt d}:1536815369\begin{verbatim}15370>>> t.append('new value')15371>>> d15372defaultdict(<class 'list'>, {'new key': ['new value']})15373\end{verbatim}1537415375If you are making a dictionary of lists, you can often write simpler15376code using {\tt defaultdict}. In my solution to15377Exercise~\ref{anagrams}, which you can get from15378\url{http://thinkpython2.com/code/anagram_sets.py}, I make a15379dictionary that maps from a sorted string of letters to the list of15380words that can be spelled with those letters. For example, {\tt15381'opst'} maps to the list {\tt ['opts', 'post', 'pots', 'spot',15382'stop', 'tops']}.1538315384Here's the original code:1538515386\begin{verbatim}15387def all_anagrams(filename):15388d = {}15389for line in open(filename):15390word = line.strip().lower()15391t = signature(word)15392if t not in d:15393d[t] = [word]15394else:15395d[t].append(word)15396return d15397\end{verbatim}1539815399This can be simplified using {\tt setdefault}, which you might15400have used in Exercise~\ref{setdefault}:15401\index{setdefault}1540215403\begin{verbatim}15404def all_anagrams(filename):15405d = {}15406for line in open(filename):15407word = line.strip().lower()15408t = signature(word)15409d.setdefault(t, []).append(word)15410return d15411\end{verbatim}1541215413This solution has the drawback that it makes a new list15414every time, regardless of whether it is needed. For lists,15415that's no big deal, but if the factory15416function is complicated, it might be.15417\index{factory function}1541815419We can avoid this problem and15420simplify the code using a {\tt defaultdict}:1542115422\begin{verbatim}15423def all_anagrams(filename):15424d = defaultdict(list)15425for line in open(filename):15426word = line.strip().lower()15427t = signature(word)15428d[t].append(word)15429return d15430\end{verbatim}1543115432My solution to Exercise~\ref{poker}, which you can download from15433\url{http://thinkpython2.com/code/PokerHandSoln.py},15434uses {\tt setdefault} in the function15435\verb"has_straightflush". This solution has the drawback15436of creating a {\tt Hand} object every time through the loop, whether15437it is needed or not. As an exercise, rewrite it using15438a defaultdict.154391544015441\section{Named tuples}1544215443Many simple objects are basically collections of related values.15444For example, the Point object defined in Chapter~\ref{clobjects} contains15445two numbers, {\tt x} and {\tt y}. When you define a class like15446this, you usually start with an init method and a str method:1544715448\begin{verbatim}15449class Point:1545015451def __init__(self, x=0, y=0):15452self.x = x15453self.y = y1545415455def __str__(self):15456return '(%g, %g)' % (self.x, self.y)15457\end{verbatim}1545815459This is a lot of code to convey a small amount of information.15460Python provides a more concise way to say the same thing:1546115462\begin{verbatim}15463from collections import namedtuple15464Point = namedtuple('Point', ['x', 'y'])15465\end{verbatim}1546615467The first argument is the name of the class you want to create.15468The second is a list of the attributes Point objects should have,15469as strings. The return value from {\tt namedtuple} is a class object:15470\index{namedtuple}15471\index{object!namedtuple}15472\index{collections}15473\index{module!collections}1547415475\begin{verbatim}15476>>> Point15477<class '__main__.Point'>15478\end{verbatim}1547915480{\tt Point} automatically provides methods like \verb"__init__" and15481\verb"__str__" so you don't have to write them.15482\index{class object}15483\index{object!class}1548415485To create a Point object, you use the Point class as a function:1548615487\begin{verbatim}15488>>> p = Point(1, 2)15489>>> p15490Point(x=1, y=2)15491\end{verbatim}1549215493The init method assigns the arguments to attributes using the names15494you provided. The str method prints a representation of the Point15495object and its attributes.1549615497You can access the elements of the named tuple by name:1549815499\begin{verbatim}15500>>> p.x, p.y15501(1, 2)15502\end{verbatim}1550315504But you can also treat a named tuple as a tuple:1550515506\begin{verbatim}15507>>> p[0], p[1]15508(1, 2)1550915510>>> x, y = p15511>>> x, y15512(1, 2)15513\end{verbatim}1551415515Named tuples provide a quick way to define simple classes.15516The drawback is that simple classes don't always stay simple.15517You might decide later that you want to add methods to a named tuple.15518In that case, you could define a new class that inherits from15519the named tuple:15520\index{inheritance}1552115522\begin{verbatim}15523class Pointier(Point):15524# add more methods here15525\end{verbatim}1552615527Or you could switch to a conventional class definition.155281552915530\section{Gathering keyword args}1553115532In Section~\ref{gather}, we saw how to write a function that15533gathers its arguments into a tuple:15534\index{gather}1553515536\begin{verbatim}15537def printall(*args):15538print(args)15539\end{verbatim}15540%15541You can call this function with any number of positional arguments15542(that is, arguments that don't have keywords):15543\index{positional argument}15544\index{argument!positional}1554515546\begin{verbatim}15547>>> printall(1, 2.0, '3')15548(1, 2.0, '3')15549\end{verbatim}15550%15551But the {\tt *} operator doesn't gather keyword arguments:15552\index{keyword argument}15553\index{argument!keyword}1555415555\begin{verbatim}15556>>> printall(1, 2.0, third='3')15557TypeError: printall() got an unexpected keyword argument 'third'15558\end{verbatim}15559%15560To gather keyword arguments, you can use the {\tt **} operator:1556115562\begin{verbatim}15563def printall(*args, **kwargs):15564print(args, kwargs)15565\end{verbatim}15566%15567You can call the keyword gathering parameter anything you want, but15568{\tt kwargs} is a common choice. The result is a dictionary that maps15569keywords to values:1557015571\begin{verbatim}15572>>> printall(1, 2.0, third='3')15573(1, 2.0) {'third': '3'}15574\end{verbatim}15575%15576If you have a dictionary of keywords and values, you can use the15577scatter operator, {\tt **} to call a function:15578\index{scatter}1557915580\begin{verbatim}15581>>> d = dict(x=1, y=2)15582>>> Point(**d)15583Point(x=1, y=2)15584\end{verbatim}15585%15586Without the scatter operator, the function would treat {\tt d} as15587a single positional argument, so it would assign {\tt d} to15588{\tt x} and complain because there's nothing to assign to {\tt y}:1558915590\begin{verbatim}15591>>> d = dict(x=1, y=2)15592>>> Point(d)15593Traceback (most recent call last):15594File "<stdin>", line 1, in <module>15595TypeError: __new__() missing 1 required positional argument: 'y'15596\end{verbatim}15597%15598When you are working with functions that have a large number of15599parameters, it is often useful to create and pass around dictionaries15600that specify frequently used options.156011560215603\section{Glossary}1560415605\begin{description}1560615607\item[conditional expression:] An expression that has one of two15608values, depending on a condition.15609\index{conditional expression}15610\index{expression!conditional}1561115612\item[list comprehension:] An expression with a {\tt for} loop in square15613brackets that yields a new list.15614\index{list comprehension}1561515616\item[generator expression:] An expression with a {\tt for} loop in parentheses15617that yields a generator object.15618\index{generator expression}15619\index{expression!generator}1562015621\item[multiset:] A mathematical entity that represents a mapping15622between the elements of a set and the number of times they appear.1562315624\item[factory:] A function, usually passed as a parameter, used to15625create objects.15626\index{factory}1562715628\end{description}1562915630156311563215633\section{Exercises}1563415635\begin{exercise}1563615637The following is a function computes the binomial15638coefficient recursively.1563915640\begin{verbatim}15641def binomial_coeff(n, k):15642"""Compute the binomial coefficient "n choose k".1564315644n: number of trials15645k: number of successes1564615647returns: int15648"""15649if k == 0:15650return 115651if n == 0:15652return 01565315654res = binomial_coeff(n-1, k) + binomial_coeff(n-1, k-1)15655return res15656\end{verbatim}1565715658Rewrite the body of the function using nested conditional15659expressions.1566015661One note: this function is not very efficient because it ends up computing15662the same values over and over. You could make it more efficient by15663memoizing (see Section~\ref{memoize}). But you will find that it's harder to15664memoize if you write it using conditional expressions.1566515666\end{exercise}15667156681566915670\appendix1567115672\chapter{Debugging}15673\index{debugging}1567415675When you are debugging, you should distinguish among different15676kinds of errors in order to track them down more quickly:1567715678\begin{itemize}1567915680\item Syntax errors are discovered by the interpreter when it is15681translating the source code into byte code. They indicate15682that there is something wrong with the structure of the program.15683Example: Omitting the colon at the end of a {\tt def} statement15684generates the somewhat redundant message {\tt SyntaxError: invalid15685syntax}.15686\index{syntax error}15687\index{error!syntax}1568815689\item Runtime errors are produced by the interpreter if something goes15690wrong while the program is running. Most runtime error messages15691include information about where the error occurred and what15692functions were executing. Example: An infinite recursion eventually15693causes the runtime error ``maximum recursion depth exceeded''.15694\index{runtime error}15695\index{error!runtime}15696\index{exception}1569715698\item Semantic errors are problems with a program that runs without15699producing error messages but doesn't do the right thing. Example:15700An expression may not be evaluated in the order you expect, yielding15701an incorrect result.15702\index{semantic error}15703\index{error!semantic}1570415705\end{itemize}1570615707The first step in debugging is to figure out which kind of15708error you are dealing with. Although the following sections are15709organized by error type, some techniques are15710applicable in more than one situation.157111571215713\section{Syntax errors}15714\index{error message}1571515716Syntax errors are usually easy to fix once you figure out what they15717are. Unfortunately, the error messages are often not helpful.15718The most common messages are {\tt SyntaxError: invalid syntax} and15719{\tt SyntaxError: invalid token}, neither of which is very informative.1572015721On the other hand, the message does tell you where in the program the15722problem occurred. Actually, it tells you where Python15723noticed a problem, which is not necessarily where the error15724is. Sometimes the error is prior to the location of the error15725message, often on the preceding line.15726\index{incremental development}15727\index{development plan!incremental}1572815729If you are building the program incrementally, you should have15730a good idea about where the error is. It will be in the last15731line you added.1573215733If you are copying code from a book, start by comparing15734your code to the book's code very carefully. Check every character.15735At the same time, remember that the book might be wrong, so15736if you see something that looks like a syntax error, it might be.1573715738Here are some ways to avoid the most common syntax errors:15739\index{syntax}1574015741\begin{enumerate}1574215743\item Make sure you are not using a Python keyword for a variable name.15744\index{keyword}1574515746\item Check that you have a colon at the end of the header of every15747compound statement, including {\tt for}, {\tt while},15748{\tt if}, and {\tt def} statements.15749\index{header}15750\index{colon}1575115752\item Make sure that any strings in the code have matching15753quotation marks. Make sure that all quotation marks are15754``straight quotes'', not ``curly quotes''.15755\index{quotation mark}1575615757\item If you have multiline strings with triple quotes (single or double), make15758sure you have terminated the string properly. An unterminated string15759may cause an {\tt invalid token} error at the end of your program,15760or it may treat the following part of the program as a string until it15761comes to the next string. In the second case, it might not produce an error15762message at all!15763\index{multiline string}15764\index{string!multiline}1576515766\item An unclosed opening operator---\verb+(+, \verb+{+, or15767\verb+[+---makes Python continue with the next line as part of the15768current statement. Generally, an error occurs almost immediately in15769the next line.1577015771\item Check for the classic {\tt =} instead of {\tt ==} inside15772a conditional.15773\index{conditional}1577415775\item Check the indentation to make sure it lines up the way it15776is supposed to. Python can handle space and tabs, but if you mix15777them it can cause problems. The best way to avoid this problem15778is to use a text editor that knows about Python and generates15779consistent indentation.15780\index{indentation}15781\index{whitespace}1578215783\item If you have non-ASCII characters in the code (including strings15784and comments), that might cause a problem, although Python 3 usually15785handles non-ASCII characters. Be careful if you paste in text from15786a web page or other source.1578715788\end{enumerate}1578915790If nothing works, move on to the next section...157911579215793\subsection{I keep making changes and it makes no difference.}1579415795If the interpreter says there is an error and you don't see it, that15796might be because you and the interpreter are not looking at the same15797code. Check your programming environment to make sure that the15798program you are editing is the one Python is trying to run.1579915800If you are not sure, try putting an obvious and deliberate syntax15801error at the beginning of the program. Now run it again. If the15802interpreter doesn't find the new error, you are not running the15803new code.1580415805There are a few likely culprits:1580615807\begin{itemize}1580815809\item You edited the file and forgot to save the changes before15810running it again. Some programming environments do this15811for you, but some don't.1581215813\item You changed the name of the file, but you are still running15814the old name.1581515816\item Something in your development environment is configured15817incorrectly.1581815819\item If you are writing a module and using {\tt import},15820make sure you don't give your module the same name as one15821of the standard Python modules.1582215823\item If you are using {\tt import} to read a module, remember15824that you have to restart the interpreter or use {\tt reload}15825to read a modified file. If you import the module again, it15826doesn't do anything.15827\index{module!reload}15828\index{reload function}15829\index{function!reload}1583015831\end{itemize}1583215833If you get stuck and you can't figure out what is going on, one15834approach is to start again with a new program like ``Hello, World!'',15835and make sure you can get a known program to run. Then gradually add15836the pieces of the original program to the new one.158371583815839\section{Runtime errors}1584015841Once your program is syntactically correct,15842Python can read it and at least start running it. What could15843possibly go wrong?158441584515846\subsection{My program does absolutely nothing.}1584715848This problem is most common when your file consists of functions and15849classes but does not actually invoke a function to start execution.15850This may be intentional if you only plan to import this module to15851supply classes and functions.1585215853If it is not intentional, make sure there is a function call15854in the program, and make sure the flow of execution reaches15855it (see ``Flow of Execution'' below).158561585715858\subsection{My program hangs.}15859\index{infinite loop}15860\index{infinite recursion}15861\index{hanging}1586215863If a program stops and seems to be doing nothing, it is ``hanging''.15864Often that means that it is caught in an infinite loop or infinite15865recursion.1586615867\begin{itemize}1586815869\item If there is a particular loop that you suspect is the15870problem, add a {\tt print} statement immediately before the loop that says15871``entering the loop'' and another immediately after that says15872``exiting the loop''.1587315874Run the program. If you get the first message and not the second,15875you've got an infinite loop. Go to the ``Infinite Loop'' section15876below.1587715878\item Most of the time, an infinite recursion will cause the program15879to run for a while and then produce a ``RuntimeError: Maximum15880recursion depth exceeded'' error. If that happens, go to the15881``Infinite Recursion'' section below.1588215883If you are not getting this error but you suspect there is a problem15884with a recursive method or function, you can still use the techniques15885in the ``Infinite Recursion'' section.1588615887\item If neither of those steps works, start testing other15888loops and other recursive functions and methods.1588915890\item If that doesn't work, then it is possible that15891you don't understand the flow of execution in your program.15892Go to the ``Flow of Execution'' section below.1589315894\end{itemize}158951589615897\subsubsection{Infinite Loop}15898\index{infinite loop}15899\index{loop!infinite}15900\index{condition}15901\index{loop!condition}1590215903If you think you have an infinite loop and you think you know15904what loop is causing the problem, add a {\tt print} statement at15905the end of the loop that prints the values of the variables in15906the condition and the value of the condition.1590715908For example:1590915910\begin{verbatim}15911while x > 0 and y < 0 :15912# do something to x15913# do something to y1591415915print('x: ', x)15916print('y: ', y)15917print("condition: ", (x > 0 and y < 0))15918\end{verbatim}15919%15920Now when you run the program, you will see three lines of output15921for each time through the loop. The last time through the15922loop, the condition should be {\tt False}. If the loop keeps15923going, you will be able to see the values of {\tt x} and {\tt y},15924and you might figure out why they are not being updated correctly.159251592615927\subsubsection{Infinite Recursion}15928\index{infinite recursion}15929\index{recursion!infinite}1593015931Most of the time, infinite recursion causes the program to run15932for a while and then produce a {\tt Maximum recursion depth exceeded}15933error.1593415935If you suspect that a function is causing an infinite15936recursion, make sure that there is a base case.15937There should be some condition that causes the15938function to return without making a recursive invocation.15939If not, you need to rethink the algorithm and identify a base15940case.1594115942If there is a base case but the program doesn't seem to be reaching15943it, add a {\tt print} statement at the beginning of the function15944that prints the parameters. Now when you run the program, you will see15945a few lines of output every time the function is invoked,15946and you will see the parameter values. If the parameters are not moving15947toward the base case, you will get some ideas about why not.159481594915950\subsubsection{Flow of Execution}15951\index{flow of execution}1595215953If you are not sure how the flow of execution is moving through15954your program, add {\tt print} statements to the beginning of each15955function with a message like ``entering function {\tt foo}'', where15956{\tt foo} is the name of the function.1595715958Now when you run the program, it will print a trace of each15959function as it is invoked.159601596115962\subsection{When I run the program I get an exception.}15963\index{exception}15964\index{runtime error}1596515966If something goes wrong during runtime, Python15967prints a message that includes the name of the15968exception, the line of the program where the problem occurred,15969and a traceback.15970\index{traceback}1597115972The traceback identifies the function that is currently running, and15973then the function that called it, and then the function that called15974{\em that}, and so on. In other words, it traces the sequence of15975function calls that got you to where you are, including the line15976number in your file where each call occurred.1597715978The first step is to examine the place in the program where15979the error occurred and see if you can figure out what happened.15980These are some of the most common runtime errors:1598115982\begin{description}1598315984\item[NameError:] You are trying to use a variable that doesn't15985exist in the current environment. Check if the name15986is spelled right, or at least consistently.15987And remember that local variables are local; you15988cannot refer to them from outside the function where they are defined.15989\index{NameError}15990\index{exception!NameError}1599115992\item[TypeError:] There are several possible causes:15993\index{TypeError}15994\index{exception!TypeError}1599515996\begin{itemize}1599715998\item You are trying to use a value improperly. Example: indexing15999a string, list, or tuple with something other than an integer.16000\index{index}1600116002\item There is a mismatch between the items in a format string and16003the items passed for conversion. This can happen if either the number16004of items does not match or an invalid conversion is called for.16005\index{format operator}16006\index{operator!format}1600716008\item You are passing the wrong number of arguments to a function.16009For methods, look at the method definition and16010check that the first parameter is {\tt self}. Then look at the16011method invocation; make sure you are invoking the method on an16012object with the right type and providing the other arguments16013correctly.1601416015\end{itemize}1601616017\item[KeyError:] You are trying to access an element of a dictionary16018using a key that the dictionary does not contain. If the keys16019are strings, remember that capitalization matters.16020\index{KeyError}16021\index{exception!KeyError}16022\index{dictionary}1602316024\item[AttributeError:] You are trying to access an attribute or method16025that does not exist. Check the spelling! You can use the built-in16026function {\tt vars} to list the attributes that do exist.16027\index{dir function}16028\index{function!dir}1602916030If an AttributeError indicates that an object has {\tt NoneType},16031that means that it is {\tt None}. So the problem is not the16032attribute name, but the object.1603316034The reason the object is none might be that you forgot16035to return a value from a function; if you get to the end of16036a function without hitting a {\tt return} statement, it returns16037{\tt None}. Another common cause is using the result from16038a list method, like {\tt sort}, that returns {\tt None}.16039\index{AttributeError}16040\index{exception!AttributeError}1604116042\item[IndexError:] The index you are using16043to access a list, string, or tuple is greater than16044its length minus one. Immediately before the site of the error,16045add a {\tt print} statement to display16046the value of the index and the length of the array.16047Is the array the right size? Is the index the right value?16048\index{IndexError}16049\index{exception!IndexError}1605016051\end{description}1605216053The Python debugger ({\tt pdb}) is useful for tracking down16054exceptions because it allows you to examine the state of the16055program immediately before the error. You can read16056about {\tt pdb} at \url{https://docs.python.org/3/library/pdb.html}.16057\index{debugger (pdb)}16058\index{pdb (Python debugger)}160591606016061\subsection{I added so many {\tt print} statements I get inundated with16062output.}16063\index{print statement}16064\index{statement!print}1606516066One of the problems with using {\tt print} statements for debugging16067is that you can end up buried in output. There are two ways16068to proceed: simplify the output or simplify the program.1606916070To simplify the output, you can remove or comment out {\tt print}16071statements that aren't helping, or combine them, or format16072the output so it is easier to understand.1607316074To simplify the program, there are several things you can do. First,16075scale down the problem the program is working on. For example, if you16076are searching a list, search a {\em small} list. If the program takes16077input from the user, give it the simplest input that causes the16078problem.16079\index{dead code}1608016081Second, clean up the program. Remove dead code and reorganize the16082program to make it as easy to read as possible. For example, if you16083suspect that the problem is in a deeply nested part of the program,16084try rewriting that part with simpler structure. If you suspect a16085large function, try splitting it into smaller functions and testing them16086separately.16087\index{testing!minimal test case}16088\index{test case, minimal}1608916090Often the process of finding the minimal test case leads you to the16091bug. If you find that a program works in one situation but not in16092another, that gives you a clue about what is going on.1609316094Similarly, rewriting a piece of code can help you find subtle16095bugs. If you make a change that you think shouldn't affect the16096program, and it does, that can tip you off.160971609816099\section{Semantic errors}1610016101In some ways, semantic errors are the hardest to debug,16102because the interpreter provides no information16103about what is wrong. Only you know what the program is supposed to16104do.16105\index{semantic error}16106\index{error!semantic}1610716108The first step is to make a connection between the program16109text and the behavior you are seeing. You need a hypothesis16110about what the program is actually doing. One of the things16111that makes that hard is that computers run so fast.1611216113You will often wish that you could slow the program down to human16114speed, and with some debuggers you can. But the time it takes to16115insert a few well-placed {\tt print} statements is often short compared to16116setting up the debugger, inserting and removing breakpoints, and16117``stepping'' the program to where the error is occurring.161181611916120\subsection{My program doesn't work.}1612116122You should ask yourself these questions:1612316124\begin{itemize}1612516126\item Is there something the program was supposed to do but16127which doesn't seem to be happening? Find the section of the code16128that performs that function and make sure it is executing when16129you think it should.1613016131\item Is something happening that shouldn't? Find code in16132your program that performs that function and see if it is16133executing when it shouldn't.1613416135\item Is a section of code producing an effect that is not16136what you expected? Make sure that you understand the code in16137question, especially if it involves functions or methods in16138other Python modules. Read the documentation for the functions you call.16139Try them out by writing simple test cases and checking the results.1614016141\end{itemize}1614216143In order to program, you need a mental model of how16144programs work. If you write a program that doesn't do what you expect,16145often the problem is not in the program; it's in your mental16146model.16147\index{model, mental}16148\index{mental model}1614916150The best way to correct your mental model is to break the program16151into its components (usually the functions and methods) and test16152each component independently. Once you find the discrepancy16153between your model and reality, you can solve the problem.1615416155Of course, you should be building and testing components as you16156develop the program. If you encounter a problem,16157there should be only a small amount of new code16158that is not known to be correct.161591616016161\subsection{I've got a big hairy expression and it doesn't16162do what I expect.}16163\index{expression!big and hairy}16164\index{big, hairy expression}1616516166Writing complex expressions is fine as long as they are readable,16167but they can be hard to debug. It is often a good idea to16168break a complex expression into a series of assignments to16169temporary variables.1617016171For example:1617216173\begin{verbatim}16174self.hands[i].addCard(self.hands[self.findNeighbor(i)].popCard())16175\end{verbatim}16176%16177This can be rewritten as:1617816179\begin{verbatim}16180neighbor = self.findNeighbor(i)16181pickedCard = self.hands[neighbor].popCard()16182self.hands[i].addCard(pickedCard)16183\end{verbatim}16184%16185The explicit version is easier to read because the variable16186names provide additional documentation, and it is easier to debug16187because you can check the types of the intermediate variables16188and display their values.16189\index{temporary variable}16190\index{variable!temporary}1619116192Another problem that can occur with big expressions is16193that the order of evaluation may not be what you expect.16194For example, if you are translating the expression16195$\frac{x}{2 \pi}$ into Python, you might write:1619616197\begin{verbatim}16198y = x / 2 * math.pi16199\end{verbatim}16200%16201That is not correct because multiplication and division have16202the same precedence and are evaluated from left to right.16203So this expression computes $x \pi / 2$.16204\index{order of operations}16205\index{precedence}1620616207A good way to debug expressions is to add parentheses to make16208the order of evaluation explicit:1620916210\begin{verbatim}16211y = x / (2 * math.pi)16212\end{verbatim}16213%16214Whenever you are not sure of the order of evaluation, use16215parentheses. Not only will the program be correct (in the sense16216of doing what you intended), it will also be more readable for16217other people who haven't memorized the order of operations.162181621916220\subsection{I've got a function that doesn't return what I16221expect.}16222\index{return statement}16223\index{statement!return}1622416225If you have a {\tt return} statement with a complex expression,16226you don't have a chance to print the result before16227returning. Again, you can use a temporary variable. For16228example, instead of:1622916230\begin{verbatim}16231return self.hands[i].removeMatches()16232\end{verbatim}16233%16234you could write:1623516236\begin{verbatim}16237count = self.hands[i].removeMatches()16238return count16239\end{verbatim}16240%16241Now you have the opportunity to display the value of16242{\tt count} before returning.162431624416245\subsection{I'm really, really stuck and I need help.}1624616247First, try getting away from the computer for a few minutes.16248Computers emit waves that affect the brain, causing these16249symptoms:1625016251\begin{itemize}1625216253\item Frustration and rage.16254\index{frustration}16255\index{rage}16256\index{debugging!emotional response}16257\index{emotional debugging}1625816259\item Superstitious beliefs (``the computer hates me'') and16260magical thinking (``the program only works when I wear my16261hat backward'').16262\index{debugging!superstition}16263\index{superstitious debugging}1626416265\item Random walk programming (the attempt to program by writing16266every possible program and choosing the one that does the right16267thing).16268\index{random walk programming}16269\index{development plan!random walk programming}1627016271\end{itemize}1627216273If you find yourself suffering from any of these symptoms, get16274up and go for a walk. When you are calm, think about the program.16275What is it doing? What are some possible causes of that16276behavior? When was the last time you had a working program,16277and what did you do next?1627816279Sometimes it just takes time to find a bug. I often find bugs16280when I am away from the computer and let my mind wander. Some16281of the best places to find bugs are trains, showers, and in bed,16282just before you fall asleep.162831628416285\subsection{No, I really need help.}1628616287It happens. Even the best programmers occasionally get stuck.16288Sometimes you work on a program so long that you can't see the16289error. You need a fresh pair of eyes.1629016291Before you bring someone else in, make sure you are prepared.16292Your program should be as simple16293as possible, and you should be working on the smallest input16294that causes the error. You should have {\tt print} statements in the16295appropriate places (and the output they produce should be16296comprehensible). You should understand the problem well enough16297to describe it concisely.1629816299When you bring someone in to help, be sure to give16300them the information they need:1630116302\begin{itemize}1630316304\item If there is an error message, what is it16305and what part of the program does it indicate?1630616307\item What was the last thing you did before this error occurred?16308What were the last lines of code that you wrote, or what is16309the new test case that fails?1631016311\item What have you tried so far, and what have you learned?1631216313\end{itemize}1631416315When you find the bug, take a second to think about what you16316could have done to find it faster. Next time you see something16317similar, you will be able to find the bug more quickly.1631816319Remember, the goal is not just to make the program16320work. The goal is to learn how to make the program work.163211632216323\chapter{Analysis of Algorithms}16324\label{algorithms}1632516326\begin{quote}16327This appendix is an edited excerpt from {\it Think Complexity}, by16328Allen B. Downey, also published by O'Reilly Media (2012). When you16329are done with this book, you might want to move on to that one.16330\end{quote}1633116332{\bf Analysis of algorithms} is a branch of computer science that16333studies the performance of algorithms, especially their run time and16334space requirements. See16335\url{http://en.wikipedia.org/wiki/Analysis_of_algorithms}.16336\index{algorithm} \index{analysis of algorithms}1633716338The practical goal of algorithm analysis is to predict the performance16339of different algorithms in order to guide design decisions.1634016341During the 2008 United States Presidential Campaign, candidate16342Barack Obama was asked to perform an impromptu analysis when16343he visited Google. Chief executive Eric Schmidt jokingly asked him16344for ``the most efficient way to sort a million 32-bit integers.''16345Obama had apparently been tipped off, because he quickly16346replied, ``I think the bubble sort would be the wrong way to go.''16347See \url{http://www.youtube.com/watch?v=k4RRi_ntQc8}.16348\index{Obama, Barack}16349\index{Schmidt, Eric}16350\index{bubble sort}1635116352This is true: bubble sort is conceptually simple but slow for16353large datasets. The answer Schmidt was probably looking for is16354``radix sort'' (\url{http://en.wikipedia.org/wiki/Radix_sort})\footnote{16355But if you get a question like this in an interview, I think16356a better answer is, ``The fastest way to sort a million integers16357is to use whatever sort function is provided by the language16358I'm using. Its performance is good enough for the vast majority16359of applications, but if it turned out that my application was too16360slow, I would use a profiler to see where the time was being16361spent. If it looked like a faster sort algorithm would have16362a significant effect on performance, then I would look16363around for a good implementation of radix sort.''}.16364\index{radix sort}1636516366The goal of algorithm analysis is to make meaningful16367comparisons between algorithms, but there are some problems:16368\index{comparing algorithms}1636916370\begin{itemize}1637116372\item The relative performance of the algorithms might16373depend on characteristics of the hardware, so one algorithm16374might be faster on Machine A, another on Machine B.16375The general solution to this problem is to specify a16376{\bf machine model} and analyze the number of steps, or16377operations, an algorithm requires under a given model.16378\index{machine model}1637916380\item Relative performance might depend on the details of16381the dataset. For example, some sorting16382algorithms run faster if the data are already partially sorted;16383other algorithms run slower in this case.16384A common way to avoid this problem is to analyze the16385{\bf worst case} scenario. It is sometimes useful to16386analyze average case performance, but that's usually harder,16387and it might not be obvious what set of cases to average over.16388\index{worst case}16389\index{average case}1639016391\item Relative performance also depends on the size of the16392problem. A sorting algorithm that is fast for small lists16393might be slow for long lists.16394The usual solution to this problem is to express run time16395(or number of operations) as a function of problem size,16396and group functions into categories depending on how quickly16397they grow as problem size increases.1639816399\end{itemize}1640016401The good thing about this kind of comparison is that it lends16402itself to simple classification of algorithms. For example,16403if I know that the run time of Algorithm A tends to be16404proportional to the size of the input, $n$, and Algorithm B16405tends to be proportional to $n^2$, then I16406expect A to be faster than B, at least for large values of $n$.1640716408This kind of analysis comes with some caveats, but we'll get16409to that later.164101641116412\section{Order of growth}1641316414Suppose you have analyzed two algorithms and expressed16415their run times in terms of the size of the input:16416Algorithm A takes $100n+1$ steps to solve a problem with16417size $n$; Algorithm B takes $n^2 + n + 1$ steps.16418\index{order of growth}1641916420The following table shows the run time of these algorithms16421for different problem sizes:1642216423\begin{tabular}{|r|r|r|}16424\hline16425Input & Run time of & Run time of \\16426size & Algorithm A & Algorithm B \\16427\hline1642810 & 1 001 & 111 \\16429100 & 10 001 & 10 101 \\164301 000 & 100 001 & 1 001 001 \\1643110 000 & 1 000 001 & 100 010 001 \\16432\hline16433\end{tabular}1643416435At $n=10$, Algorithm A looks pretty bad; it takes almost 10 times16436longer than Algorithm B. But for $n=100$ they are about the same, and16437for larger values A is much better.1643816439The fundamental reason is that for large values of $n$, any function16440that contains an $n^2$ term will grow faster than a function whose16441leading term is $n$. The {\bf leading term} is the term with the16442highest exponent.16443\index{leading term}16444\index{exponent}1644516446For Algorithm A, the leading term has a large coefficient, 100, which16447is why B does better than A for small $n$. But regardless of the16448coefficients, there will always be some value of $n$ where16449$a n^2 > b n$, for any values of $a$ and $b$.16450\index{leading coefficient}1645116452The same argument applies to the non-leading terms. Even if the run16453time of Algorithm A were $n+1000000$, it would still be better than16454Algorithm B for sufficiently large $n$.1645516456In general, we expect an algorithm with a smaller leading term to be a16457better algorithm for large problems, but for smaller problems, there16458may be a {\bf crossover point} where another algorithm is better. The16459location of the crossover point depends on the details of the16460algorithms, the inputs, and the hardware, so it is usually ignored for16461purposes of algorithmic analysis. But that doesn't mean you can forget16462about it.16463\index{crossover point}1646416465If two algorithms have the same leading order term, it is hard to say16466which is better; again, the answer depends on the details. So for16467algorithmic analysis, functions with the same leading term16468are considered equivalent, even if they have different coefficients.1646916470An {\bf order of growth} is a set of functions whose growth16471behavior is considered equivalent. For example, $2n$, $100n$ and $n+1$16472belong to the same order of growth, which is written $O(n)$ in16473{\bf Big-Oh notation} and often called {\bf linear} because every function16474in the set grows linearly with $n$.16475\index{big-oh notation}16476\index{linear growth}1647716478All functions with the leading term $n^2$ belong to $O(n^2)$; they are16479called {\bf quadratic}.16480\index{quadratic growth}1648116482The following table shows some of the orders of growth that16483appear most commonly in algorithmic analysis,16484in increasing order of badness.16485\index{badness}1648616487\begin{tabular}{|r|r|r|}16488\hline16489Order of & Name \\16490growth & \\16491\hline16492$O(1)$ & constant \\16493$O(\log_b n)$ & logarithmic (for any $b$) \\16494$O(n)$ & linear \\16495$O(n \log_b n)$ & linearithmic \\16496$O(n^2)$ & quadratic \\16497$O(n^3)$ & cubic \\16498$O(c^n)$ & exponential (for any $c$) \\16499\hline16500\end{tabular}1650116502For the logarithmic terms, the base of the logarithm doesn't matter;16503changing bases is the equivalent of multiplying by a constant, which16504doesn't change the order of growth. Similarly, all exponential16505functions belong to the same order of growth regardless of the base of16506the exponent.16507Exponential functions grow very quickly, so exponential algorithms are16508only useful for small problems.16509\index{logarithmic growth}16510\index{exponential growth}165111651216513\begin{exercise}1651416515Read the Wikipedia page on Big-Oh notation at16516\url{http://en.wikipedia.org/wiki/Big_O_notation} and16517answer the following questions:1651816519\begin{enumerate}16520\item What is the order of growth of $n^3 + n^2$?16521What about $1000000 n^3 + n^2$?16522What about $n^3 + 1000000 n^2$?1652316524\item What is the order of growth of $(n^2 + n) \cdot (n + 1)$? Before16525you start multiplying, remember that you only need the leading term.1652616527\item If $f$ is in $O(g)$, for some unspecified function $g$, what can16528we say about $af+b$, where $a$ and $b$ are constants?1652916530\item If $f_1$ and $f_2$ are in $O(g)$, what can we say about $f_1 + f_2$?1653116532\item If $f_1$ is in $O(g)$16533and $f_2$ is in $O(h)$,16534what can we say about $f_1 + f_2$?1653516536\item If $f_1$ is in $O(g)$ and $f_2$ is $O(h)$,16537what can we say about $f_1 \cdot f_2$?16538\end{enumerate}1653916540\end{exercise}1654116542Programmers who care about performance often find this kind of16543analysis hard to swallow. They have a point: sometimes the16544coefficients and the non-leading terms make a real difference.16545Sometimes the details of the hardware, the programming language, and16546the characteristics of the input make a big difference. And for small16547problems, order of growth is irrelevant.1654816549But if you keep those caveats in mind, algorithmic analysis is a16550useful tool. At least for large problems, the ``better'' algorithm16551is usually better, and sometimes it is {\em much} better. The16552difference between two algorithms with the same order of growth is16553usually a constant factor, but the difference between a good algorithm16554and a bad algorithm is unbounded!165551655616557\section{Analysis of basic Python operations}1655816559In Python, most arithmetic operations are constant time;16560multiplication usually takes longer than addition and subtraction, and16561division takes even longer, but these run times don't depend on the16562magnitude of the operands. Very large integers are an exception; in16563that case the run time increases with the number of digits.16564\index{analysis of primitives}1656516566Indexing operations---reading or writing elements in a sequence16567or dictionary---are also constant time, regardless of the size16568of the data structure.16569\index{indexing}1657016571A {\tt for} loop that traverses a sequence or dictionary is16572usually linear, as long as all of the operations in the body16573of the loop are constant time. For example, adding up the16574elements of a list is linear:1657516576\begin{verbatim}16577total = 016578for x in t:16579total += x16580\end{verbatim}1658116582The built-in function {\tt sum} is also linear because it does16583the same thing, but it tends to be faster because it is a more16584efficient implementation; in the language of algorithmic analysis,16585it has a smaller leading coefficient.1658616587As a rule of thumb, if the body of a loop is in $O(n^a)$ then16588the whole loop is in $O(n^{a+1})$. The exception is if you can16589show that the loop exits after a constant number of iterations.16590If a loop runs $k$ times regardless of $n$, then16591the loop is in $O(n^a)$, even for large $k$.1659216593Multiplying by $k$ doesn't change the order of growth, but neither16594does dividing. So if the body of a loop is in $O(n^a)$ and it runs16595$n/k$ times, the loop is in $O(n^{a+1})$, even for large $k$.1659616597Most string and tuple operations are linear, except indexing and {\tt16598len}, which are constant time. The built-in functions {\tt min} and16599{\tt max} are linear. The run-time of a slice operation is16600proportional to the length of the output, but independent of the size16601of the input.16602\index{string methods}16603\index{tuple methods}1660416605String concatenation is linear; the run time depends on the sum16606of the lengths of the operands.16607\index{string concatenation}1660816609All string methods are linear, but if the lengths of16610the strings are bounded by a constant---for example, operations on single16611characters---they are considered constant time.16612The string method {\tt join} is linear; the run time depends on16613the total length of the strings.16614\index{join@{\tt join}}1661516616Most list methods are linear, but there are some exceptions:16617\index{list methods}1661816619\begin{itemize}1662016621\item Adding an element to the end of a list is constant time on16622average; when it runs out of room it occasionally gets copied16623to a bigger location, but the total time for $n$ operations16624is $O(n)$, so the average time for each16625operation is $O(1)$.1662616627\item Removing an element from the end of a list is constant time.1662816629\item Sorting is $O(n \log n)$.16630\index{sorting}1663116632\end{itemize}1663316634Most dictionary operations and methods are constant time, but16635there are some exceptions:16636\index{dictionary methods}1663716638\begin{itemize}1663916640\item The run time of {\tt update} is16641proportional to the size of the dictionary passed as a parameter,16642not the dictionary being updated.1664316644\item {\tt keys}, {\tt values} and {\tt items} are constant time because16645they return iterators. But16646if you loop through the iterators, the loop will be linear.16647\index{iterator}1664816649\end{itemize}1665016651The performance of dictionaries is one of the minor miracles of16652computer science. We will see how they work in16653Section~\ref{hashtable}.166541665516656\begin{exercise}1665716658Read the Wikipedia page on sorting algorithms at16659\url{http://en.wikipedia.org/wiki/Sorting_algorithm} and answer16660the following questions:16661\index{sorting}1666216663\begin{enumerate}1666416665\item What is a ``comparison sort?'' What is the best worst-case order16666of growth for a comparison sort? What is the best worst-case order16667of growth for any sort algorithm?16668\index{comparison sort}1666916670\item What is the order of growth of bubble sort, and why does Barack16671Obama think it is ``the wrong way to go?''1667216673\item What is the order of growth of radix sort? What preconditions16674do we need to use it?1667516676\item What is a stable sort and why might it matter in practice?16677\index{stable sort}1667816679\item What is the worst sorting algorithm (that has a name)?1668016681\item What sort algorithm does the C library use? What sort algorithm16682does Python use? Are these algorithms stable? You might have to16683Google around to find these answers.1668416685\item Many of the non-comparison sorts are linear, so why does does16686Python use an $O(n \log n)$ comparison sort?1668716688\end{enumerate}1668916690\end{exercise}166911669216693\section{Analysis of search algorithms}1669416695A {\bf search} is an algorithm that takes a collection and a target16696item and determines whether the target is in the collection, often16697returning the index of the target.16698\index{search}1669916700The simplest search algorithm is a ``linear search'', which traverses16701the items of the collection in order, stopping if it finds the target.16702In the worst case it has to traverse the entire collection, so the run16703time is linear.16704\index{linear search}1670516706The {\tt in} operator for sequences uses a linear search; so do string16707methods like {\tt find} and {\tt count}.16708\index{in@{\tt in} operator}1670916710If the elements of the sequence are in order, you can use a {\bf16711bisection search}, which is $O(\log n)$. Bisection search is16712similar to the algorithm you might use to look a word up in a16713dictionary (a paper dictionary, not the data structure). Instead of16714starting at the beginning and checking each item in order, you start16715with the item in the middle and check whether the word you are looking16716for comes before or after. If it comes before, then you search the16717first half of the sequence. Otherwise you search the second half.16718Either way, you cut the number of remaining items in half.16719\index{bisection search}1672016721If the sequence has 1,000,000 items, it will take about 20 steps to16722find the word or conclude that it's not there. So that's about 50,00016723times faster than a linear search.1672416725Bisection search can be much faster than linear search, but16726it requires the sequence to be in order, which might require16727extra work.1672816729There is another data structure, called a {\bf hashtable} that16730is even faster---it can do a search in constant time---and it16731doesn't require the items to be sorted. Python dictionaries16732are implemented using hashtables, which is why most dictionary16733operations, including the {\tt in} operator, are constant time.167341673516736\section{Hashtables}16737\label{hashtable}1673816739To explain how hashtables work and why their performance is so16740good, I start with a simple implementation of a map and16741gradually improve it until it's a hashtable.16742\index{hashtable}1674316744I use Python to demonstrate these implementations, but in real16745life you wouldn't write code like this in Python; you would just use a16746dictionary! So for the rest of this chapter, you have to imagine that16747dictionaries don't exist and you want to implement a data structure16748that maps from keys to values. The operations you have to16749implement are:1675016751\begin{description}1675216753\item[{\tt add(k, v)}:] Add a new item that maps from key {\tt k}16754to value {\tt v}. With a Python dictionary, {\tt d}, this operation16755is written {\tt d[k] = v}.1675616757\item[{\tt get(k)}:] Look up and return the value that corresponds16758to key {\tt k}. With a Python dictionary, {\tt d}, this operation16759is written {\tt d[k]} or {\tt d.get(k)}.1676016761\end{description}1676216763For now, I assume that each key only appears once.16764The simplest implementation of this interface uses a list of16765tuples, where each tuple is a key-value pair.16766\index{LinearMap@{\tt LinearMap}}1676716768\begin{verbatim}16769class LinearMap:1677016771def __init__(self):16772self.items = []1677316774def add(self, k, v):16775self.items.append((k, v))1677616777def get(self, k):16778for key, val in self.items:16779if key == k:16780return val16781raise KeyError16782\end{verbatim}1678316784{\tt add} appends a key-value tuple to the list of items, which16785takes constant time.1678616787{\tt get} uses a {\tt for} loop to search the list:16788if it finds the target key it returns the corresponding value;16789otherwise it raises a {\tt KeyError}.16790So {\tt get} is linear.16791\index{KeyError@{\tt KeyError}}1679216793An alternative is to keep the list sorted by key. Then {\tt get}16794could use a bisection search, which is $O(\log n)$. But inserting a16795new item in the middle of a list is linear, so this might not be the16796best option. There are other data structures that can implement {\tt16797add} and {\tt get} in log time, but that's still not as good as16798constant time, so let's move on.16799\index{red-black tree}1680016801One way to improve {\tt LinearMap} is to break the list of key-value16802pairs into smaller lists. Here's an implementation called16803{\tt BetterMap}, which is a list of 100 LinearMaps. As we'll see16804in a second, the order of growth for {\tt get} is still linear,16805but {\tt BetterMap} is a step on the path toward hashtables:16806\index{BetterMap@{\tt BetterMap}}1680716808\begin{verbatim}16809class BetterMap:1681016811def __init__(self, n=100):16812self.maps = []16813for i in range(n):16814self.maps.append(LinearMap())1681516816def find_map(self, k):16817index = hash(k) % len(self.maps)16818return self.maps[index]1681916820def add(self, k, v):16821m = self.find_map(k)16822m.add(k, v)1682316824def get(self, k):16825m = self.find_map(k)16826return m.get(k)16827\end{verbatim}1682816829\verb"__init__" makes a list of {\tt n} {\tt LinearMap}s.1683016831\verb"find_map" is used by16832{\tt add} and {\tt get}16833to figure out which map to put the16834new item in, or which map to search.1683516836\verb"find_map" uses the built-in function {\tt hash}, which takes16837almost any Python object and returns an integer. A limitation of this16838implementation is that it only works with hashable keys. Mutable16839types like lists and dictionaries are unhashable.16840\index{hash function}1684116842Hashable objects that are considered equivalent return the same hash16843value, but the converse is not necessarily true: two objects with16844different values can return the same hash value.1684516846\verb"find_map" uses the modulus operator to wrap the hash values16847into the range from 0 to {\tt len(self.maps)}, so the result is a legal16848index into the list. Of course, this means that many different16849hash values will wrap onto the same index. But if the hash function16850spreads things out pretty evenly (which is what hash functions16851are designed to do), then we expect $n/100$ items per LinearMap.1685216853Since the run time of {\tt LinearMap.get} is proportional to the16854number of items, we expect BetterMap to be about 100 times faster16855than LinearMap. The order of growth is still linear, but the16856leading coefficient is smaller. That's nice, but still not16857as good as a hashtable.1685816859Here (finally) is the crucial idea that makes hashtables fast: if you16860can keep the maximum length of the LinearMaps bounded, {\tt16861LinearMap.get} is constant time. All you have to do is keep track16862of the number of items and when the number of16863items per LinearMap exceeds a threshold, resize the hashtable by16864adding more LinearMaps.16865\index{bounded}1686616867Here is an implementation of a hashtable:16868\index{HashMap}1686916870\begin{verbatim}16871class HashMap:1687216873def __init__(self):16874self.maps = BetterMap(2)16875self.num = 01687616877def get(self, k):16878return self.maps.get(k)1687916880def add(self, k, v):16881if self.num == len(self.maps.maps):16882self.resize()1688316884self.maps.add(k, v)16885self.num += 11688616887def resize(self):16888new_maps = BetterMap(self.num * 2)1688916890for m in self.maps.maps:16891for k, v in m.items:16892new_maps.add(k, v)1689316894self.maps = new_maps16895\end{verbatim}1689616897\verb"__init__" creates a {\tt BetterMap} and initializes {\tt num}, which keeps track of the number of items.1689816899{\tt get} just dispatches to {\tt BetterMap}. The real work happens16900in {\tt add}, which checks the number of items and the size of the16901{\tt BetterMap}: if they are equal, the average number of items per16902LinearMap is 1, so it calls {\tt resize}.1690316904{\tt resize} make a new {\tt BetterMap}, twice as big as the previous16905one, and then ``rehashes'' the items from the old map to the new.1690616907Rehashing is necessary because changing the number of LinearMaps16908changes the denominator of the modulus operator in16909\verb"find_map". That means that some objects that used16910to hash into the same LinearMap will get split up (which is16911what we wanted, right?).16912\index{rehashing}1691316914Rehashing is linear, so16915{\tt resize} is linear, which might seem bad, since I promised16916that {\tt add} would be constant time. But remember that16917we don't have to resize every time, so {\tt add} is usually16918constant time and only occasionally linear. The total amount16919of work to run {\tt add} $n$ times is proportional to $n$,16920so the average time of each {\tt add} is constant time!16921\index{constant time}1692216923To see how this works, think about starting with an empty16924HashTable and adding a sequence of items. We start with 2 LinearMaps,16925so the first 2 adds are fast (no resizing required). Let's16926say that they take one unit of work each. The next add16927requires a resize, so we have to rehash the first two16928items (let's call that 2 more units of work) and then16929add the third item (one more unit). Adding the next item16930costs 1 unit, so the total so far is169316 units of work for 4 items.1693216933The next {\tt add} costs 5 units, but the next three16934are only one unit each, so the total is 14 units for the16935first 8 adds.1693616937The next {\tt add} costs 9 units, but then we can add 7 more16938before the next resize, so the total is 30 units for the16939first 16 adds.1694016941After 32 adds, the total cost is 62 units, and I hope you are starting16942to see a pattern. After $n$ adds, where $n$ is a power of two, the16943total cost is $2n-2$ units, so the average work per add is16944a little less than 2 units. When $n$ is a power of two, that's16945the best case; for other values of $n$ the average work is a little16946higher, but that's not important. The important thing is that it16947is $O(1)$.16948\index{average cost}1694916950Figure~\ref{fig.hash} shows how this works graphically. Each16951block represents a unit of work. The columns show the total16952work for each add in order from left to right: the first two16953{\tt adds} cost 1 unit each, the third costs 3 units, etc.1695416955\begin{figure}16956\centerline{\includegraphics[width=5.5in]{figs/towers.pdf}}16957\caption{The cost of a hashtable add.\label{fig.hash}}16958\end{figure}1695916960The extra work of rehashing appears as a sequence of increasingly16961tall towers with increasing space between them. Now if you knock16962over the towers, spreading the cost of resizing over all16963adds, you can see graphically that the total cost after $n$16964adds is $2n - 2$.1696516966An important feature of this algorithm is that when we resize the16967HashTable it grows geometrically; that is, we multiply the size by a16968constant. If you increase the size16969arithmetically---adding a fixed number each time---the average time16970per {\tt add} is linear.16971\index{geometric resizing}1697216973You can download my implementation of HashMap from16974\url{http://thinkpython2.com/code/Map.py}, but remember that there16975is no reason to use it; if you want a map, just use a Python dictionary.1697616977\section{Glossary}1697816979\begin{description}1698016981\item[analysis of algorithms:] A way to compare algorithms in terms of16982their run time and/or space requirements.16983\index{analysis of algorithms}1698416985\item[machine model:] A simplified representation of a computer used16986to describe algorithms.16987\index{machine model}1698816989\item[worst case:] The input that makes a given algorithm run slowest (or16990require the most space).16991\index{worst case}1699216993\item[leading term:] In a polynomial, the term with the highest exponent.16994\index{leading term}1699516996\item[crossover point:] The problem size where two algorithms require16997the same run time or space.16998\index{crossover point}1699917000\item[order of growth:] A set of functions that all grow in a way17001considered equivalent for purposes of analysis of algorithms.17002For example, all functions that grow linearly belong to the same17003order of growth.17004\index{order of growth}1700517006\item[Big-Oh notation:] Notation for representing an order of growth;17007for example, $O(n)$ represents the set of functions that grow17008linearly.17009\index{Big-Oh notation}1701017011\item[linear:] An algorithm whose run time is proportional to17012problem size, at least for large problem sizes.17013\index{linear}1701417015\item[quadratic:] An algorithm whose run time is proportional to17016$n^2$, where $n$ is a measure of problem size.17017\index{quadratic}1701817019\item[search:] The problem of locating an element of a collection17020(like a list or dictionary) or determining that it is not present.17021\index{search}1702217023\item[hashtable:] A data structure that represents a collection of17024key-value pairs and performs search in constant time.17025\index{hashtable}1702617027\end{description}170281702917030\printindex1703117032\clearemptydoublepage17033%\blankpage17034%\blankpage17035%\blankpage170361703717038\end{document}170391704017041