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.

58 Chapter 6. Fruitful functionsfibonacci(0)=0fibonacci(1)=1Translated into <strong>Python</strong>, itlooks likethis:fibonacci(n)=fibonacci(n−1)+fibonacci(n−2);def fibonacci (n):if n == 0:return 0elif n == 1:return 1else:return fibonacci(n-1) + fibonacci(n-2)Ifyoutrytofollowtheflowofexecutionhere,evenforfairlysmallvaluesofn,yourheadexplodes.But according to the leap of faith, if you assume that the two recursive calls work correctly, then itisclear that you get the right resultby adding them together.6.8 CheckingtypesWhat happens ifwecallfactorialand give it1.5as an argument?>>> factorial(1.5)RuntimeError: Maximum recursion depth exceededIt looks like an infinite recursion. But how can that be? There is a base case—when n == 0. But ifnisnot aninteger, we can missthebase case and recurseforever.In the first recursive call, the value of n is 0.5. In the next, it is -0.5. From there, it gets smaller(morenegative), but it willnever be0.We have two choices. We can try to generalize the factorial function to work with floating-pointnumbers, or we can make factorial check the type of its argument. The first option is called thegamma function 2 and it’salittlebeyond thescope of thisbook. Sowe’ll gofor thesecond.We can use the built-in function isinstance to verify the type of the argument. While we’re at it,wecan alsomake suretheargument ispositive:def factorial (n):if not isinstance(n, int):print 'Factorial is only defined for integers.'return Noneelif n < 0:print 'Factorial is not defined for negative integers.'return Noneelif n == 0:return 1else:return n * factorial(n-1)2 Seewikipedia.org/wiki/Gamma_function.

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

Saved successfully!

Ooh no, something went wrong!