introduction to recursion (python)

80
Recursion Extracted 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

Upload: thai-pangsakulyanont

Post on 25-May-2015

598 views

Category:

Technology


6 download

DESCRIPTION

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

TRANSCRIPT

Page 1: Introduction to Recursion (Python)

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 PangsakulyanontSoftware and Knowledge Engineering Undergraduate Student

Kasetsart University

Page 3: Introduction to Recursion (Python)
Page 4: Introduction to Recursion (Python)
Page 5: Introduction to Recursion (Python)
Page 6: Introduction to Recursion (Python)

Read this sentence and do what it says twice.

http://programmers.stackexchange.com/a/93858

Page 7: Introduction to Recursion (Python)

n! =

(1 if n = 0

(n � 1)!⇥ n if n > 0

Page 8: Introduction to Recursion (Python)

Factorial Examplen! =

(1 if n = 0

(n � 1)!⇥ n if n > 0

3!

Page 9: Introduction to Recursion (Python)

Factorial Example

3!

n! =

(1 if n = 0

(n � 1)!⇥ n if n > 0

= (3 - 1)! × 3

Page 10: Introduction to Recursion (Python)

Factorial Example

3!

n! =

(1 if n = 0

(n � 1)!⇥ n if n > 0

= (3 - 1)! × 3= 2! × 3

Page 11: Introduction to Recursion (Python)

Factorial Example

3!

n! =

(1 if n = 0

(n � 1)!⇥ n if n > 0

= (3 - 1)! × 3= 2! × 3

We turn this problem into asmaller problem of same kind.This is called “decomposition.”

Page 12: Introduction to Recursion (Python)

Factorial Example

3!

n! =

(1 if n = 0

(n � 1)!⇥ n if n > 0

= (3 - 1)! × 3= 2! × 3

2! = (2 - 1)! × 2

Page 13: Introduction to Recursion (Python)

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

Page 14: Introduction to Recursion (Python)

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

Page 15: Introduction to Recursion (Python)

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

Page 16: Introduction to Recursion (Python)

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

Page 17: Introduction to Recursion (Python)

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.

Page 18: Introduction to Recursion (Python)

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

Page 19: Introduction to Recursion (Python)

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

Page 20: Introduction to Recursion (Python)

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 problemto find the result of larger problem.

This is called “composition”.

Page 21: Introduction to Recursion (Python)

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

Page 22: Introduction to Recursion (Python)

Factorial Example

3!

n! =

(1 if n = 0

(n � 1)!⇥ n if n > 0

= (3 - 1)! × 3= 2! × 3= 2 × 3= 6.

Page 23: Introduction to Recursion (Python)

def fac(n): if n == 0: return 1 else: return fac(n - 1) * n

print fac(12)

Factorial Example

Page 24: Introduction to Recursion (Python)

Recursive Function

• A function that calls itself!

Page 25: Introduction to Recursion (Python)

Count Down

countdown(5)print "happy recursion day"

Page 26: Introduction to Recursion (Python)

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.

Page 27: Introduction to Recursion (Python)

Countdown Exampledef countdown(n): if n == 0: return print n countdown(n - 1)

countdown(5)print "happy recursion day"

Page 28: Introduction to Recursion (Python)

Example:Euclidean Algorithm

• Fast way to find a GCDof two numbers.

Page 29: Introduction to Recursion (Python)

Example:Euclidean Algorithm

If you have 2 numbers,then you subtract the smaller number

from the larger number, the GCD of thesetwo number stays the same.

Page 30: Introduction to Recursion (Python)

Example:Euclidean Algorithm

68 119GCD(68, 119) is 17

Page 31: Introduction to Recursion (Python)

Example:Euclidean Algorithm

68 119

GCD(68, 51) is still 17

68 51

Page 32: Introduction to Recursion (Python)

Example:Euclidean Algorithm

If you have 2 numbers,then you subtract the smaller number

from the larger number, the GCD of thesetwo number stays the same.

Keep doing that until the two numbersequal each other, then that number is the GCD.

Page 33: Introduction to Recursion (Python)

Example:Euclidean Algorithm

GCD(68, 119)

Page 34: Introduction to Recursion (Python)

Example:Euclidean Algorithm

GCD(68, 119) = GCD(68, 51)

Page 35: Introduction to Recursion (Python)

Example:Euclidean Algorithm

GCD(68, 119) = GCD(68, 51)= GCD(17, 51)

Page 36: Introduction to Recursion (Python)

Example:Euclidean Algorithm

GCD(68, 119) = GCD(68, 51)= GCD(17, 51)= GCD(17, 34)

Page 37: Introduction to Recursion (Python)

Example:Euclidean Algorithm

GCD(68, 119) = GCD(68, 51)= GCD(17, 51)= GCD(17, 34)= GCD(17, 17)

Page 38: Introduction to Recursion (Python)

Example:Euclidean Algorithm

GCD(68, 119) = GCD(68, 51)= GCD(17, 51)= GCD(17, 34)= GCD(17, 17)= 17

Page 39: Introduction to Recursion (Python)

Example:Euclidean Algorithmdef 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)

Page 40: Introduction to Recursion (Python)

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) # = gcd(21990955, 21) # = gcd(21990934, 21)

Page 41: Introduction to Recursion (Python)

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)

Page 42: Introduction to Recursion (Python)

Why Recursion?

• Sometimes it’s easier to write and read code in recursive form.

Page 43: Introduction to Recursion (Python)

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.

Page 44: Introduction to Recursion (Python)

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)

Page 45: Introduction to Recursion (Python)

IterativeEuclidean 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)

Page 46: Introduction to Recursion (Python)

Remember?

• Decomposition

• Base Case

• Composition

Page 47: Introduction to Recursion (Python)

String Reversal

• Given a string, I want a reversed version of that string.

print reverse("reenigne")

# => “engineer”

Page 48: Introduction to Recursion (Python)

String Reversal

• Let’s think recursively!

reenigne

Page 49: Introduction to Recursion (Python)

Decomposition

r eenigne

Page 50: Introduction to Recursion (Python)

Recursive Case

r enginee

eenignesomehow

Page 51: Introduction to Recursion (Python)

Composition

renginee

Page 52: Introduction to Recursion (Python)

Composition

engineer

Page 53: Introduction to Recursion (Python)

?

eenigne

enginee

Page 54: Introduction to Recursion (Python)

e

eenigneenigneeengine

enginee

Page 55: Introduction to Recursion (Python)

Base Case

• The reverse of an empty string is an empty string.

Page 56: Introduction to Recursion (Python)

Recursive Algorithm

reverse(“Hello”)

Page 57: Introduction to Recursion (Python)

Recursive Algorithm

reverse(“Hello”) = reverse(“ello”) + “H”

Page 58: Introduction to Recursion (Python)

Recursive Algorithm

reverse(“Hello”) = reverse(“ello”) + “H”

reverse(“ello”) = reverse(“llo”) + “e”

Page 59: Introduction to Recursion (Python)

Recursive Algorithm

reverse(“Hello”) = reverse(“ello”) + “H”

reverse(“ello”) = reverse(“llo”) + “e”

reverse(“llo”) = reverse(“lo”) + “l”

Page 60: Introduction to Recursion (Python)

Recursive Algorithm

reverse(“Hello”) = reverse(“ello”) + “H”

reverse(“ello”) = reverse(“llo”) + “e”

reverse(“llo”) = reverse(“lo”) + “l”

reverse(“lo”) = reverse(“o”) + “l”

Page 61: Introduction to Recursion (Python)

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”

Page 62: Introduction to Recursion (Python)

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(“”) = “”

Page 63: Introduction to Recursion (Python)

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”

Page 64: Introduction to Recursion (Python)

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”

Page 65: Introduction to Recursion (Python)

Recursive Algorithm

reverse(“Hello”) = reverse(“ello”) + “H”

reverse(“ello”) = reverse(“llo”) + “e”

reverse(“llo”) = reverse(“lo”) + “l” = “ol” + “l” = “oll”

Page 66: Introduction to Recursion (Python)

Recursive Algorithm

reverse(“Hello”) = reverse(“ello”) + “H”

reverse(“ello”) = reverse(“llo”) + “e” = “oll” + “e” = “olle”

Page 67: Introduction to Recursion (Python)

Recursive Algorithm

reverse(“Hello”) = reverse(“ello”) + “H” = “olle” + “H” = “olleH”

Page 68: Introduction to Recursion (Python)

Reverse Example

def reverse(str): if str == "": return str # or return “” else: return reverse(str[1:]) + str[0]

print reverse("reenigne")

Page 69: Introduction to Recursion (Python)

print sum_digits(314159265) # => 36

Sum of Digits

Page 70: Introduction to Recursion (Python)

print sum_digits(314159265) # => 36

Sum of Digits

• NO LOOPS!

• NO STRINGS!

Page 71: Introduction to Recursion (Python)

Recursive Algorithm

• Sum of digits of 0 is 0.

• Sum of digits of N > 0: Find last digit + sum of digits except last.

Page 72: Introduction to Recursion (Python)

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

Page 73: Introduction to Recursion (Python)

Sum of Digits

def sum_digits(n): if n == 0: return 0 else: return (n % 10) + sum_digits(n // 10)

print sum_digits(314159265)

Page 74: Introduction to Recursion (Python)

Palindrome

CivicLevel

MadamMalayalam

RadarReviverRotatorTerret

Page 75: Introduction to Recursion (Python)

print is_palindrome("Refer") # => True

print is_palindrome("Referrer") # => False

Page 76: Introduction to Recursion (Python)

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.

Page 77: Introduction to Recursion (Python)

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.

Page 78: Introduction to Recursion (Python)

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") # => Trueprint is_palindrome("Referrer") # => False

Page 79: Introduction to Recursion (Python)

def is_palindrome(s): return reverse(s.lower()) == s.lower() print is_palindrome("Refer") # => Trueprint is_palindrome("Referrer") # => False

def reverse(str): if str == "": return str else: return reverse(str[1:]) + str[0]

Page 80: Introduction to Recursion (Python)

Exercise!