CS 149
Professor: Alvin Chao
Definitions
Recursion
Thinking recursively is easy if you can recognize a subtask that is similar to the original task. - Horstman Big Java ���Humorous quote:
There are two kinds of people in the world, those who divide the world into two kinds of people and those who do not
What do these have in common?
Using Recursion in definitions: Factorial
Example: Fibonacci Numbers
Recursion
”In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.” Source: https://en.wikipedia.org/wiki/Factorial
If we repeatedly break down a problem into smaller versions of itself, we eventually reach a basic problem that can’t be broken down any further. Such a problem, like 0!, is referred to as the base case.
Factorial with loops
Recursion Trace
Recursion Trace questions
Designing Recursive Algorithms
Recursion - Factorials
Fibbonacci numbers
The Fibonacci numbers are a sequence where every number (after the first two) is the sum of the two preceding numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, . . .
Source: https://en.wikipedia.org/wiki/Fibonacci_number
We can define a recursive function to compute Fibonacci numbers. Enter the following code into a Python Editor, and run the program to see the sequence.
fibonacci
Questions
Summation
”In mathematics, summation (capital Greek sigma symbol: Σ) is the addition of a sequence of numbers; the result is their sum or total.”
100�∑i = 1+2+3+...+100 = 5050 i=1 Source: https://en.wikipedia.org/wiki/Summation�
Consider how to calculate ∑ i = 10.
a) Write out all the numbers that need to be added:
1+2+3+4
b) Show how this sum can be calculated in terms of a smaller summation.
N + sum of i for n-1
What is the base case for the summation? i = 1
Recursive summation
def summation(n):
if n == 1:
return 1
else:
return n + summation(n - 1)
Recursion tracing
PI Question
Tests for PA2B
[L] (N) _N_ (T) [N] a b c d e
_ _E_ _ _S_ _N_ f h j
(I) _I_ [O] _U_ (A) k l m n o
_ _R_ _ (S) _O_ p r t
[D] _W_ (G) _K_ [Y] u v w x y
Starter file text:
[L],(N),_N_,(T),[N]
___,_E_,___,_S_,_N_
(I),_I_,[O],_U_,(A)
___,_R_,___,(S),_O_
[D],_W_,(G),_K_,[Y]
Solution file text:
[L],[O],[G],[I],[N]
[I],[_],[R],[_],[A]
[K],[N],[O],[W],[N]
[E],[_],[S],[_],[N]
[D],[U],[S],[T],[Y]
U] (A) (E) _O_ [T] a b c d e
_L_ _ [H] _ _K_ f h j
(L) _E_ [U] (E) (K) k l m n o
(P) _ _N_ _ (A) p r t
[T] _C_ (S) _S_ [N] u v w x y
Starter file text:
[U],(A),(E),_O_,[T]
_L_,___,[H],___,_K_
(L),_E_,[U],(E),(K)
(P),___,_N_,___,(A)
[T],_C_,(S),_S_,[N]
Solution file text:
[U],[N],[S],[E],[T]
[P],[_],[H],[_],[A]
[S],[K],[U],[L],[L]
[E],[_],[C],[_],[O]
[T],[A],[K],[E],[N]
Parts of this activity are based on materials developed by Chris Mayfield and Nathan Sprague.
</end>