What is recursion & backtracking in Python?


Recursion 

Recursion is useful in dividing and solving problems. Each recursive call itself spins off other recursive calls. At the centre of a recursive function are two types of cases: base cases, which tell the recursion when to terminate, and recursive cases that call the function they are in. A simple problem that naturally uses recursive solutions is calculating factorials. The recursive factorial algorithm has two cases: the base case when n = 0, and the recursive case when n>0 . 

Backtracking

Backtracking is a general algorithm for finding solutions to some computational problem, that incrementally builds choices to the solutions, and rejects continued processing of tracks that would lead to impossible solutions. Backtracking allows us to undo previous choices if  they turn out to be mistakes.

A typical implementation of the factorial is the following -

Example

def factorial(n):
  #test for a base case
     if n==0:
       return 1
         # make a calculation and a recursive call
         f= n*factorial(n-1)
     print(f)
  return(f)
factorial(4)

This code prints out the digits 1, 2, 4, 24. To calculate factorial 4 requires four recursive calls plus the initial parent call. 

Updated on: 19-Feb-2020

621 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements