Recursion Discussion 7
Recursion Discussion 7
Discussion 7
Factorial in Snap
using factorial (5)
as an example
in the previous slide, 5! could be represented as 5 x 4! = 5 x
4 x 3! and etc.
the same logic applies for this Snap version
factorial (5) = 5 x factorial (4) = 5 x 4 x factorial (3), and etc.
the recursion finally ends at factorial (1), when our block just
reports 1, not calling itself again
Factorial in Snap
think of this recursive process like a ladder (you go down the ladder until
you hit the base case, then you go back up to evaluate and compute the
values)
factorial (3) = 6
3 x factorial (2)
2 x factorial (1)
1
Recursion
Base Case(s):
Recursive Case(s):
Recursion
Base Case(s):
-Simplest form of the problem
Recursive Case(s):
Recursion
Base Case(s):
-Simplest form of the problem
Recursive Case(s):
-Divide problem into smaller instances
Recursion
Base Case(s):
-Simplest form of the problem
Recursive Case(s):
-Divide problem into smaller instances
-Invoke function (recursively)
Recursion
Base Case(s):
-Simplest form of the problem
Recursive Case(s):
-Divide problem into smaller instances
-Invoke function (recursively)
-Work towards base case
fib (0)
0
fib (2)
fib (1)
1
fib (1)
fib (0)
=1+0+1+1+0=3
Practice Problems
Note: Most of these problems will require you to first import
the List Utilities and Words, sentences libraries.
Also remember to use recursion in your solutions.
HINT:
O.N.I.F.C.F.I.N.O.
A palindrome is a word that is spelled the same way
forwards and backwards (example: racecar). Given a word
as input, report whether or not the word is a palindrome.
HINTS:
O.N.I.F.C.F.I.N.O.
Smack My List Up
Given a list as input, report the reverse of the list
HINTS:
Smack My List Up
Original List
Ladder Fractal
Rectangle Fractal