Recursion vs Iteration
Reversing a String
• How about reversing a string? Of course, we can just use string slicing
• How about we write a function for it?
Reverse String (Iterative Version 1)
i l-i-1 s[l-i-1] output
0 4 e e
1 3 d ed
2 2 c edc
3 1 b edcb
4 0 a edcba
Reverse String (Iterative Version 1)
i l-i-1 s[l-i-1] output
0 4 e e
1 3 d ed
2 2 c edc
3 1 b edcb
4 0 a edcba
Reverse String (Iterative Version 1)
i l-i-1 s[l-i-1] output
0 4 e e
1 3 d ed
2 2 c edc
3 1 b edcb
4 0 a edcba
Reverse String (Iterative Version 1)
i l-i-1 s[l-i-1] output
0 4 e e
1 3 d ed
2 2 c edc
3 1 b edcb
4 0 a edcba
Reverse String (Iterative Version 2)
c output
a a
b ba
c cba
d dbca
e edbca
Reversing String (Recursive Version)
• reverseStringR(‘abcde’)
• reverseStringR(‘bcde’)+’a’
• reverseStringR(‘cde’)+’b’+’a’
• reverseStringR(‘de’)+’c’+’b’+’a’
• reverseStringR(‘e’)+’d’+’c’+’b’+’a’
• reverseStringR(‘’)+’e’+’d’+’c’+’b’+’a’
• ‘’+’e’+’d’+’c’+’b’+’a’
• ‘edcba’
Taylor Series
Taylor Series
n=1 n=2 n=3
• We do not need the infinite precision
• We may just sum up to k terms
k
Computing sine by Iteration
k
• Using iteration
Python Library version of “sin()”
Computing sine by Recursion
Sum up to n = 2
Sum up to n = 1
• In general, if we want to sum up to the k terms
Sum up to n = k
k
kth
Sum up to n = k - 1
n=k
Computing sine by Recursion
• Assuming that if the function sinR(x,k) sums until n = k, then
sinR(x,k) = sinR(x,k-1) + the kth term
• In general, if we want to sum up to the k terms
Sum up to n = k
k
kth
Sum up to n = k - 1
n=k
Computing sine by Recursion
• Assuming that if the function sinR(x,k) sums until n = k, then
sinR(x,k) = sinR(x,k-1) + the kth term
More Taylor Series
Recursion Common Patterns
Base cases
Recursion step to reduce the problem one-by-one
Iteration Common Patterns
Accumulate element one-by-one
Initial the final answer to “nothing” at the beginning.
Accumulate and return the final answer
Iteration/Recursion Conversion
Base case The answer for previous k – 1 terms The kth term
Iteration/Recursion Conversion
Base case The answer for previous k – 1 terms The kth term
“Homework”
• The answer for all k-1 terms?
• Base case?
• Kth term?
“Homework”
• How to re-write your code with both iterative/recursion version
mentioned in this course before?
• burgerPrice()
• checkAllAlpha()
• Etc.
• The answer for all k-1 terms?
• Base case?
• Kth term?
Code Refactoring
Code Refactoring
• Refactoring is a disciplined technique for restructuring an existing
body of code, altering its internal structure without changing its
external behavior.