RecursionExtracted from my lecture during A. Paruj Ratanaworabhan’s
basic preparatory programming course for freshmen:
Int...
http://greatingpoint.co.th/?
showpage=product&file=product_detail&prd_id=1328776222
Read this sentence and
do what it says twice.
http://programmers.stackexchange.com/a/93858
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
Factorial Example
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
3!
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
We turn this problem into a
smaller pro...
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)...
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)...
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)...
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)...
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)...
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)...
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)...
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
= 1 × 2 = 2
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
= 2 × 3
= 6.
def fac(n):
if n == 0:
return 1
else:
return fac(n - 1) * n
print fac(12)
Factorial Example
Recursive Function
• A function that calls itself!
Count Down
countdown(5)
print "happy recursion day"
Countdown Algorithm
• If I want to countdown from 0,
then it’s over! Don’t do anything.
• If I want to countdown from N (>...
Countdown Example
def countdown(n):
if n == 0:
return
print n
countdown(n - 1)
countdown(5)
print "happy recursion day"
Example:
Euclidean Algorithm
• Fast way to find a GCD
of two numbers.
Example:
Euclidean Algorithm
If you have 2 numbers,
then you subtract the smaller number
from the larger number, the GCD o...
Example:
Euclidean Algorithm
68 119
GCD(68, 119) is 17
Example:
Euclidean Algorithm
68 119
GCD(68, 51) is still 17
68 51
Example:
Euclidean Algorithm
If you have 2 numbers,
then you subtract the smaller number
from the larger number, the GCD o...
Example:
Euclidean Algorithm
GCD(68, 119)
Example:
Euclidean Algorithm
GCD(68, 119) = GCD(68, 51)
Example:
Euclidean Algorithm
GCD(68, 119) = GCD(68, 51)
= GCD(17, 51)
Example:
Euclidean Algorithm
GCD(68, 119) = GCD(68, 51)
= GCD(17, 51)
= GCD(17, 34)
Example:
Euclidean Algorithm
GCD(68, 119) = GCD(68, 51)
= GCD(17, 51)
= GCD(17, 34)
= GCD(17, 17)
Example:
Euclidean Algorithm
GCD(68, 119) = GCD(68, 51)
= GCD(17, 51)
= GCD(17, 34)
= GCD(17, 17)
= 17
Example:
Euclidean Algorithm
def gcd(a, b):
if a < b:
return gcd(a, b - a)
elif b < a:
return gcd(a - b, b)
else:
return a...
Who Says It’s Fast?
print gcd(21991144, 21)
# = gcd(21991123, 21)
# = gcd(21991102, 21)
# = gcd(21991081, 21)
# = gcd(2199...
It’s Actually Really Fast
Consider:
(56, 10) → (46, 10) → (36, 10) →
(26, 10) → (16, 10) → (6, 10)
56 % 10 = 6
(the rest o...
Why Recursion?
• Sometimes it’s easier to write and read
code in recursive form.
Why Recursion?
• Sometimes it’s easier to write and read
code in recursive form.
• You can always convert an iterative
alg...
Why Recursion?
• Sometimes it’s easier to write and read
code in recursive form.
• You can always convert an iterative
alg...
Iterative
Euclidean Algorithm
def gcd(a, b):
while a != b:
if a < b:
b = b - a
elif b < a:
a = a - b
return a
print gcd(68...
Remember?
• Decomposition
• Base Case
• Composition
String Reversal
• Given a string, I want a reversed version
of that string.
print reverse("reenigne")
# => “engineer”
String Reversal
• Let’s think recursively!
reenigne
Decomposition
r eenigne
Recursive Case
r enginee
eenigne
somehow
Composition
renginee
Composition
engineer
?
eenigne
enginee
e
eenigne
enignee
engine
enginee
Base Case
• The reverse of an empty string is an
empty string.
Recursive Algorithm
reverse(“Hello”)
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = rever...
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = rever...
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = rever...
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = rever...
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = rever...
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = rever...
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = rever...
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
= “oll” + “e” = “olle”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
= “olle” + “H”
= “olleH”
Reverse Example
def reverse(str):
if str == "":
return str # or return “”
else:
return reverse(str[1:]) + str[0]
print rev...
print sum_digits(314159265) # => 36
Sum of Digits
print sum_digits(314159265) # => 36
Sum of Digits
• NO LOOPS!
• NO STRINGS!
Recursive Algorithm
• Sum of digits of 0 is 0.
• Sum of digits of N > 0:
Find last digit + sum of digits except last.
Recursive Algorithm
• Sum of digits of 0 is 0.
• Sum of digits of N > 0:
Find last digit + sum of digits except last.
N % ...
Sum of Digits
def sum_digits(n):
if n == 0:
return 0
else:
return (n % 10) + sum_digits(n // 10)
print sum_digits(31415926...
Palindrome
Civic
Level
Madam
Malayalam
Radar
Reviver
Rotator
Terret
print is_palindrome("Refer") # => True
print is_palindrome("Referrer") # => False
Recursive Algorithm
• Empty string is a palindrome.
• String with 1 character is a palindrome.
• String that has a differe...
Recursive Algorithm
• Empty string is a palindrome.
• String with 1 character is a palindrome.
• String that has a differe...
def is_palindrome(s):
if len(s) < 2:
return True
if s[0].lower() != s[-1].lower():
return False
return is_palindrome(s[1:-...
def is_palindrome(s):
return reverse(s.lower()) == s.lower()
print is_palindrome("Refer") # => True
print is_palindrome("R...
Exercise!
Introduction to Recursion (Python)
Introduction to Recursion (Python)
Introduction to Recursion (Python)
Upcoming SlideShare
Loading in …5
×

Introduction to Recursion (Python)

5,022 views

Published on

A presentation about the ideas of recursion and recursive functions.

This is my lecture presentation during A. Paruj Ratanaworabhan’s basic preparatory programming course for freshmen: Introduction to Programming: A Tutorial for New Comers Using Python

Published in: Technology
0 Comments
8 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
5,022
On SlideShare
0
From Embeds
0
Number of Embeds
22
Actions
Shares
0
Downloads
136
Comments
0
Likes
8
Embeds 0
No embeds

No notes for slide

Introduction to Recursion (Python)

  1. 1. RecursionExtracted from my lecture during A. Paruj Ratanaworabhan’s basic preparatory programming course for freshmen: Introduction to Programming: A Tutorial for New Comers Using Python By Thai Pangsakulyanont Software and Knowledge Engineering Undergraduate Student Kasetsart University
  2. 2. http://greatingpoint.co.th/? showpage=product&file=product_detail&prd_id=1328776222
  3. 3. Read this sentence and do what it says twice. http://programmers.stackexchange.com/a/93858
  4. 4. n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0
  5. 5. Factorial Example n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 3!
  6. 6. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3
  7. 7. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3
  8. 8. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 We turn this problem into a smaller problem of same kind. This is called “decomposition.”
  9. 9. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 2! = (2 - 1)! × 2
  10. 10. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 2! = (2 - 1)! × 2 = 1! × 2
  11. 11. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 2! = (2 - 1)! × 2 = 1! × 2 1! = (1 - 1)! × 1
  12. 12. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 2! = (2 - 1)! × 2 = 1! × 2 1! = (1 - 1)! × 1 = 0! × 1
  13. 13. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 2! = (2 - 1)! × 2 = 1! × 2 1! = (1 - 1)! × 1 = 0! × 1 0! = 1
  14. 14. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 2! = (2 - 1)! × 2 = 1! × 2 1! = (1 - 1)! × 1 = 0! × 1 0! = 1 This is called the “base case” where the function does not call itself anymore.
  15. 15. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 2! = (2 - 1)! × 2 = 1! × 2 1! = (1 - 1)! × 1 = 0! × 1 0! = 1
  16. 16. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 2! = (2 - 1)! × 2 = 1! × 2 1! = (1 - 1)! × 1 = 0! × 1 = 1 × 1 = 1
  17. 17. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 2! = (2 - 1)! × 2 = 1! × 2 1! = (1 - 1)! × 1 = 0! × 1 = 1 × 1 = 1 We use the result of smaller problem to find the result of larger problem. This is called “composition”.
  18. 18. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 2! = (2 - 1)! × 2 = 1! × 2 = 1 × 2 = 2
  19. 19. Factorial Example 3! n! = ( 1 if n = 0 (n 1)! ⇥ n if n > 0 = (3 - 1)! × 3 = 2! × 3 = 2 × 3 = 6.
  20. 20. def fac(n): if n == 0: return 1 else: return fac(n - 1) * n print fac(12) Factorial Example
  21. 21. Recursive Function • A function that calls itself!
  22. 22. Count Down countdown(5) print "happy recursion day"
  23. 23. Countdown Algorithm • If I want to countdown from 0, then it’s over! Don’t do anything. • If I want to countdown from N (> 0), then count N, and countdown from N-1.
  24. 24. Countdown Example def countdown(n): if n == 0: return print n countdown(n - 1) countdown(5) print "happy recursion day"
  25. 25. Example: Euclidean Algorithm • Fast way to find a GCD of two numbers.
  26. 26. Example: Euclidean Algorithm If you have 2 numbers, then you subtract the smaller number from the larger number, the GCD of these two number stays the same.
  27. 27. Example: Euclidean Algorithm 68 119 GCD(68, 119) is 17
  28. 28. Example: Euclidean Algorithm 68 119 GCD(68, 51) is still 17 68 51
  29. 29. Example: Euclidean Algorithm If you have 2 numbers, then you subtract the smaller number from the larger number, the GCD of these two number stays the same. Keep doing that until the two numbers equal each other, then that number is the GCD.
  30. 30. Example: Euclidean Algorithm GCD(68, 119)
  31. 31. Example: Euclidean Algorithm GCD(68, 119) = GCD(68, 51)
  32. 32. Example: Euclidean Algorithm GCD(68, 119) = GCD(68, 51) = GCD(17, 51)
  33. 33. Example: Euclidean Algorithm GCD(68, 119) = GCD(68, 51) = GCD(17, 51) = GCD(17, 34)
  34. 34. Example: Euclidean Algorithm GCD(68, 119) = GCD(68, 51) = GCD(17, 51) = GCD(17, 34) = GCD(17, 17)
  35. 35. Example: Euclidean Algorithm GCD(68, 119) = GCD(68, 51) = GCD(17, 51) = GCD(17, 34) = GCD(17, 17) = 17
  36. 36. Example: Euclidean Algorithm def gcd(a, b): if a < b: return gcd(a, b - a) elif b < a: return gcd(a - b, b) else: return a print gcd(68, 119)
  37. 37. Who Says It’s Fast? print gcd(21991144, 21) # = gcd(21991123, 21) # = gcd(21991102, 21) # = gcd(21991081, 21) # = gcd(21991060, 21) # = gcd(21991039, 21) # = gcd(21991018, 21) # = gcd(21990997, 21) # = gcd(21990976, 21)
  38. 38. It’s Actually Really Fast Consider: (56, 10) → (46, 10) → (36, 10) → (26, 10) → (16, 10) → (6, 10) 56 % 10 = 6 (the rest of this is for your exercise)
  39. 39. Why Recursion? • Sometimes it’s easier to write and read code in recursive form.
  40. 40. Why Recursion? • Sometimes it’s easier to write and read code in recursive form. • You can always convert an iterative algorithm to recursive and vice versa.
  41. 41. Why Recursion? • Sometimes it’s easier to write and read code in recursive form. • You can always convert an iterative algorithm to recursive and vice versa. (does not mean it’s easy)
  42. 42. Iterative Euclidean Algorithm def gcd(a, b): while a != b: if a < b: b = b - a elif b < a: a = a - b return a print gcd(68, 119)
  43. 43. Remember? • Decomposition • Base Case • Composition
  44. 44. String Reversal • Given a string, I want a reversed version of that string. print reverse("reenigne") # => “engineer”
  45. 45. String Reversal • Let’s think recursively! reenigne
  46. 46. Decomposition r eenigne
  47. 47. Recursive Case r enginee eenigne somehow
  48. 48. Composition renginee
  49. 49. Composition engineer
  50. 50. ? eenigne enginee
  51. 51. e eenigne enignee engine enginee
  52. 52. Base Case • The reverse of an empty string is an empty string.
  53. 53. Recursive Algorithm reverse(“Hello”)
  54. 54. Recursive Algorithm reverse(“Hello”) = reverse(“ello”) + “H”
  55. 55. Recursive Algorithm reverse(“Hello”) = reverse(“ello”) + “H” reverse(“ello”) = reverse(“llo”) + “e”
  56. 56. Recursive Algorithm reverse(“Hello”) = reverse(“ello”) + “H” reverse(“ello”) = reverse(“llo”) + “e” reverse(“llo”) = reverse(“lo”) + “l”
  57. 57. Recursive Algorithm reverse(“Hello”) = reverse(“ello”) + “H” reverse(“ello”) = reverse(“llo”) + “e” reverse(“llo”) = reverse(“lo”) + “l” reverse(“lo”) = reverse(“o”) + “l”
  58. 58. Recursive Algorithm reverse(“Hello”) = reverse(“ello”) + “H” reverse(“ello”) = reverse(“llo”) + “e” reverse(“llo”) = reverse(“lo”) + “l” reverse(“lo”) = reverse(“o”) + “l” reverse(“o”) = reverse(“”) + “o”
  59. 59. Recursive Algorithm reverse(“Hello”) = reverse(“ello”) + “H” reverse(“ello”) = reverse(“llo”) + “e” reverse(“llo”) = reverse(“lo”) + “l” reverse(“lo”) = reverse(“o”) + “l” reverse(“o”) = reverse(“”) + “o” reverse(“”) = “”
  60. 60. Recursive Algorithm reverse(“Hello”) = reverse(“ello”) + “H” reverse(“ello”) = reverse(“llo”) + “e” reverse(“llo”) = reverse(“lo”) + “l” reverse(“lo”) = reverse(“o”) + “l” reverse(“o”) = reverse(“”) + “o” = “” + “o” = “o”
  61. 61. Recursive Algorithm reverse(“Hello”) = reverse(“ello”) + “H” reverse(“ello”) = reverse(“llo”) + “e” reverse(“llo”) = reverse(“lo”) + “l” reverse(“lo”) = reverse(“o”) + “l” = “o” + “l” = “ol”
  62. 62. Recursive Algorithm reverse(“Hello”) = reverse(“ello”) + “H” reverse(“ello”) = reverse(“llo”) + “e” reverse(“llo”) = reverse(“lo”) + “l” = “ol” + “l” = “oll”
  63. 63. Recursive Algorithm reverse(“Hello”) = reverse(“ello”) + “H” reverse(“ello”) = reverse(“llo”) + “e” = “oll” + “e” = “olle”
  64. 64. Recursive Algorithm reverse(“Hello”) = reverse(“ello”) + “H” = “olle” + “H” = “olleH”
  65. 65. Reverse Example def reverse(str): if str == "": return str # or return “” else: return reverse(str[1:]) + str[0] print reverse("reenigne")
  66. 66. print sum_digits(314159265) # => 36 Sum of Digits
  67. 67. print sum_digits(314159265) # => 36 Sum of Digits • NO LOOPS! • NO STRINGS!
  68. 68. Recursive Algorithm • Sum of digits of 0 is 0. • Sum of digits of N > 0: Find last digit + sum of digits except last.
  69. 69. Recursive Algorithm • Sum of digits of 0 is 0. • Sum of digits of N > 0: Find last digit + sum of digits except last. N % 10 N // 10
  70. 70. Sum of Digits def sum_digits(n): if n == 0: return 0 else: return (n % 10) + sum_digits(n // 10) print sum_digits(314159265)
  71. 71. Palindrome Civic Level Madam Malayalam Radar Reviver Rotator Terret
  72. 72. print is_palindrome("Refer") # => True print is_palindrome("Referrer") # => False
  73. 73. Recursive Algorithm • Empty string is a palindrome. • String with 1 character is a palindrome. • String that has a different first character and last character is not a palindrome.
  74. 74. Recursive Algorithm • Empty string is a palindrome. • String with 1 character is a palindrome. • String that has a different first character and last character is not a palindrome. • String that has a same first and last character is a palindrome only if the string without first and last character is a palindrome.
  75. 75. def is_palindrome(s): if len(s) < 2: return True if s[0].lower() != s[-1].lower(): return False return is_palindrome(s[1:-1]) print is_palindrome("Refer") # => True print is_palindrome("Referrer") # => False
  76. 76. def is_palindrome(s): return reverse(s.lower()) == s.lower() print is_palindrome("Refer") # => True print is_palindrome("Referrer") # => False def reverse(str): if str == "": return str else: return reverse(str[1:]) + str[0]
  77. 77. Exercise!

×