# CSS 220 In-Class Activity

CSS 220 In-Class Activity

Just \$7 Welcome

Recursion is often described as something defined in terms of itself. In fact, if we look up recursion in the Urban dictionary, we will find the humorous, but accurate, entry “Recursion: see recursion”

1. Play the Towers of Hanoi game for 3, 4, and 5, discs. Paste the images of your completed game below. Play at this link: https://www.mathsisfun.com/games/towerofhanoi.html

Let’s take a look at the algorithm and answer the following

Watch this video for a visualization of the code below: https://www.youtube.com/watch?v=YstLjLCGmgg

def TowersOfHanoi (n , r1, r3, r2):

if n == 1:

print (“Move disk 1 from rod”, r1,”to rod”, r3)

return

else:

TowersOfHanoi (n-1, r1, r2, r3)

print (“Move disk”,n,”from rod”, r1,”to rod”, r3)

TowersOfHanoi (n-1, r2, r3, r1)

TowesrOfHanoi(4,”A”,”C”,”B”)

2. In Towers of Hanoi how many times is the recursive move_disks() function invoked for 3 disks?

a. 3

b. 4

c. 7

d. 14

3. In Towers of Hanoi how many times is the recursive move_disks() function invoked for 4 disks?

a. 5

b. 10

c. 15

d. 20

4. What is the result of “print (mystery(648))” call?

def mystery (n): if (n<10): return n else: a = n // 10 # floor division b = n % 10 return mystery (a + b) print (mystery(648))

a. 8

b. 9

c. 54

d. 72

e. 648

5. Recursively solve: ( (1+2) * (8-3) ) + ( (4*5) – (9/3) )

6. Fill in the blanks to complete the code to count the length of a string.

def recLen (string): if ______________________: ________________________ else: return 1 + recLen (string[1:])

print (“The length of the string “apple” is “, recLen(“apple”))

7. What is the return value for xfunction(4) after calling the following function?

def xfunction(n):     if n == 1:         return 1;     else:         return n + xfunction(n – 1)