#3 Recursion, Loops, Stack
#3 Recursion, Loops, Stack
Loops, Stack
Data Structures and Algorithms
Objectives:
Recursion is a
programming
technique where a
function calls itself
within its own
definition.
Recursion
It is usually used to
solve problems that
can be broken down
into smaller instances
of the same problem
(divide and conquer).
Suppose there is a locked
suitcase. To open the
suitcase, you need to find the
key for its lock.
You have been informed that
the key is inside a box.
The box where the key is found,
however, contains many
smaller boxes. The key is inside
one of the smaller boxes.
How would you look for the
key?
You might try doing
something like this, a step-
by-step procedure to look
through each box.
You might also try something
like this.
Which approach seems
easier for you, the left or
the right?
This approach uses a
While Loop.
It is where a function
calls itself.
The pseudocode for this
approach might look
like this…
Both approaches
accomplish the same
thing, but recursion
may seem to be
clearer.
Loop vs. Recursion
Because a recursive
function calls itself, it’s
easy to write a function
incorrectly that ends up
in an infinite loop.
An infinite loop is a
function that will keep If you execute an infinite loop in Python,
executing forever. you can kill the script with the keyboard
shortcut Ctrl - C
Base Case and Recursive Case
• Basic Operations on
Stacks
o Insertion: push()
o Deletion: pop()
Hands-On Demo
Recursion and Stacks