Download Lecture 10: Reasoning About Recursion

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Lecture 10: Reasoning About Recursion
CS6507– Python Programming and Data Science Applications
Dr Kieran T. Herley
Department of Computer Science
University College Cork
2015/16
KH (10/03/16)
Lecture 10: Reasoning About Recursion
2015/16
1 / 23
Summary
Recursive Fibonacci function. Reasoning about
same. Recursion trees. Mathematical induction.
N-Queens problem.
KH (10/03/16)
Lecture 10: Reasoning About Recursion
2015/16
2 / 23
Recursion Basics
Fibonacci Numbers
The Fibonacci sequence is defined as follows:
Each number is the sum of the two preceding ones
The first two numbers are 0 and 1
The sequence begins:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, · · ·
1
4
Symbol = denotes “is defined to be”.
KH (10/03/16)
Lecture 10: Reasoning About Recursion
2015/16
3 / 23
Recursion Basics
Fibonacci Numbers
The Fibonacci sequence is defined as follows:
Each number is the sum of the two preceding ones
The first two numbers are 0 and 1
The sequence begins:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, · · ·
Can re-state definition s following equation or recursive function:
4
fn =
1
n
fn−2 + fn−1
if n ≤ 1
if n > 1.
def fib (n):
if n <= 1:
return n
else :
return fib (n−2) + fib(n−1)
1
4
Symbol = denotes “is defined to be”.
KH (10/03/16)
Lecture 10: Reasoning About Recursion
2015/16
3 / 23
Recursion Basics
Anatomy of a recursive function
def fib (n):
if n <= 1:
return n
else :
return fib (n−2) + fib(n−1)
Recursive functions contains
Base Case(s) Simple case; solves problem directly; no recursion.
Recursive Case(s) fib(n) “delegates”/“subcontracts” work to fib(n-2)
and {fib(n-1)
KH (10/03/16)
Lecture 10: Reasoning About Recursion
2015/16
4 / 23
Recursion Basics
Reasoning about fib’s execution
def fib (n):
if n <= 1:
return n
else :
return fib (n−2) + fib(n−1)
fib(5) computation entails many (15) calls to fib function
“Operational” reasoning– mentally tracing execution in your head– is
problematic.
What’s the alternative?
KH (10/03/16)
Lecture 10: Reasoning About Recursion
2015/16
5 / 23
Related documents