How to create recursive function
Recursive function
Recursion is a way to call a function from inside its own declaration.
A recursive function usually consists of the following parts:
A base case when the function returns a value directly. A recursive case, which contains one or more recursive calls on smaller parts of the problem.
Compute the factorial of a number n. The factorial of n is defined as n x (n?1) x (n?2) x . . . x 1.
The mathematical definition of the factorial, which can be stated as follows:
- The factorial of 1 is 1.
- The factorial of a number n greater than 1 is the product of n and the factorial of n?1.
def factorial(n):
if n == 1: # w ww . j ava 2 s . co m
return 1
else:
return n * factorial(n-1)
print factorial(10);
The code above generates the following result.
Recursive search function
def search(sequence, number, lower, upper):
if lower == upper:
assert number == sequence[upper]
return upper
else: # w w w . j a va2 s.co m
middle = (lower + upper) // 2
if number > sequence[middle]:
return search(sequence, number, middle+1, upper)
else:
return search(sequence, number, lower, middle)
seq = [ 6,8, 7, 23, 100]
seq.sort()
print seq
print search(seq, 4)
print search(seq, 100)