Did you ever have to work on a code where you had to repeat the same lines over and over again? Where you had to work on a really big and complex problem?
Well, one way of dealing with those situations would be to use recursion. Recursion is the process of breaking down big, complex problems into smaller, simpler ones. These smaller problems are, in fact, repetitions of the bigger ones. Recursion is pretty similar to the divide and conquer technique. Instead of tackling a really perplex problem, we break it down into smaller instances of itself and work on those easier ones, then combine all the solutions obtained to get a better understanding of the bigger, complex problem.
Here's one example of recursion which we did in our 4th lab:
def bin_rep(n):
"""
Produce the binary string representing non-negative integer n in binary.
>>> bin_rep(0)
'0'
>>> bin_rep(1)
'1'
>>> bin_rep(5)
'101'
"""
if n == 1:
return '1'
elif n == 0:
return '0'
else:
return bin_rep(n // 2) + bin_rep(n % 2)
So here, when n is greater than 1, the method bin_rep will repeat itself until n has broken down to 1 or 0. Lets say n is 500. Recursion will automatically break n down until it has become 0 or 1, recording all the solutions along the way.
I think that without recursion, the life of computer programmers would be really difficult. Recursion helps a lot when working on complex codes. It facilitate our job and is also better looking than 100+ amount of lines for only one code.
No comments:
Post a Comment