12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

6.5. More recursion 55It is common to give boolean functions names that sound like yes/no questions; is_divisiblereturns eitherTrueorFalsetoindicate whetherxisdivisible byy.Here isanexample:>>> is_divisible(6, 4)False>>> is_divisible(6, 3)TrueTheresultofthe==operator isaboolean, sowecan writethefunctionmoreconcisely byreturningitdirectly:def is_divisible(x, y):return x % y == 0Boolean functions areoften used inconditional statements:if is_divisible(x, y):print 'x is divisible by y'Itmight be tempting towritesomething like:if is_divisible(x, y) == True:print 'x is divisible by y'But the extra comparison isunnecessary.Exercise 6.3 Write a function is_between(x, y, z) that returns True if x ≤ y ≤ z or Falseotherwise.6.5 MorerecursionWe have only covered a small subset of <strong>Python</strong>, but you might be interested to know that thissubset is a complete programming language, which means that anything that can be computed canbeexpressedinthislanguage. Anyprogrameverwrittencouldberewrittenusingonlythelanguagefeatures you have learned so far (actually, you would need a few commands to control devices likethekeyboard, mouse, disks,etc., but that’sall).Proving that claim is a nontrivial exercise first accomplished by Alan Turing, one of the first computerscientists(somewouldarguethathewasamathematician,butalotofearlycomputerscientistsstartedasmathematicians). Accordingly,itisknownastheTuringThesis. Foramorecomplete(andaccurate) discussion of the Turing Thesis, I recommend Michael Sipser’s book Introduction to theTheory of Computation.To give you an idea of what you can do with the tools you have learned so far, we’ll evaluate a fewrecursively defined mathematical functions. Arecursive definition issimilartoacircular definition,in the sense that the definition contains a reference to the thing being defined. A truly circulardefinition isnot very useful:frabjous: An adjective used todescribe something that isfrabjous.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!