03 Recursion
03 Recursion
03 Recursion
Rahul Narain
a = False
b = True
c = True In this case output will
def mean(a, b): be -- b is true
print('before return') if a:
return (a + b)/2 print('a is true')
print('after return') elif b:
print('b is true')
four = mean(3, 5) elif c:
print('c is true')
else:
print('none are true')
The moment we return the value, we go out of
the function.
Output mei bas before return show hoga after
return nahi
By the way, it’s a good idea to document your code using comments:
print('before return')
return (a + b)/2 # This is the actual calculation
# Nothing after this point will run
print('after return')
Conditionals again IMPORTANT
The code in the branches can include anything, including other ifs:
if condition1:
if condition2:
print('case A')
else:
print('case B')
else:
if condition3:
print('case C')
else:
print('case D')
You can prompt the user to enter some text using the input function.
To figure out how to do arbitrarily many steps, break the problem down
into (i) one step, and (ii) the rest of the steps.
a × b = a + a + a + ··· + a
| {z }
b times
= a + a + a + ··· + a
| {z }
b − 1 times
= a + a × (b − 1):
4×3=4+4×2
= 4 + (4 + 4 × 1)
= 4 + (4 + (4 + 4 × 0))
= 4 + (4 + (4 + (4 + 4 × (0 − 1))))
| {z }
???
?
a × b = a + a × (b − 1):
(
0 if b = 0,
a×b =
a + a × (b − 1) otherwise.
n! = 1 × 2 × · · · × (n − 1) × n
Is this enough?
(
1 if n = 0,
n! =
(n − 1)! × n otherwise.
def fact(n):
# The factorial of a natural number n.
if n == 0:
return 1
else:
return fact(n - 1) * n
There isn’t always just one way to do it!
` ´
n! = 1 × 2 × 3 · · · × (n − 1) × n
“ ` ´”
= 1 × 2 × 3 × : : : · · · × (n − 1) × n
..
.
n! = p(1; n);
?
p(a; b) = a × p(a + 1; b):
0; 1; 1; 2; 3; 5; 8; 13; : : :
After the first two numbers, every number is the sum of the previous two
numbers.
This is also a recursive definition:
8
<0
> if n = 0,
Fn = 1 if n = 1,
>
Fn−1 + Fn−2 otherwise.
:
Exercise: Write a program to compute the 10th, 20th, and 30th Fibonacci
numbers.
def fib(n):
# The nth Fibonacci number.
# [Write this code yourself :)]
print(fib(10))
print(fib(20))
print(fib(30))
7000
6000
5000
3000
These numbers are growing exponentially!
2000
1000
5 10 15 20
Let’s move away from Python for a bit, and consider a real-world example.
Dictionaries contain words in alphabetical order. How do you look up a
word in a dictionary? Can you describe it as an algorithm?
Bisection