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.11. Exercises 61sum = x + y + zpow = b(sum)**2return powx = 1y = x + 1print c(x, y+3, x+y)Exercise 6.5 The Ackermann function, A(m,n),isdefined 3 :⎧⎪⎨ n+1 ifm=0A(m,n)= A(m−1,1) ifm>0and n=0⎪⎩A(m−1,A(m,n−1)) ifm>0and n>0.(6.1)Write a function named ack that evaluates Ackerman’s function. Use your function to evaluateack(3, 4),which should be125. What happens for larger values ofmandn?Exercise 6.6 A palindrome is a word that is spelled the same backward and forward, like “noon”and “redivider”. Recursively, a word is a palindrome if the first and last letters are the same and themiddle isapalindrome.The following arefunctions that take astringargument and returnthefirst,last,and middle letters:def first(word):return word[0]def last(word):return word[-1]def middle(word):return word[1:-1]We’ll seehow they work inChapter 8.1. Type these functions into a file named palindrome.py and test them out. What happens ifyou call middle with a string with two letters? One letter? What about the empty string,which iswritten'' and contains noletters?2. Write a function called is_palindrome that takes a string argument and returns True if it isa palindrome and False otherwise. Remember that you can use the built-in function len tocheck thelength of astring.Exercise 6.7 A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write afunction calledis_powerthat takes parametersaandband returnsTrueifaisapower ofb.Exercise6.8 Thegreatestcommondivisor(GCD)ofaandbisthelargestnumberthatdividesbothof them withno remainder 4 .3 Seewikipedia.org/wiki/Ackermann_function.4 ThisexerciseisbasedonanexamplefromAbelsonandSussman’sStructureandInterpretationofComputerPrograms.

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

Saved successfully!

Ooh no, something went wrong!