What is called recursive function in python?
In this tutorial, you will learn to create a recursive function (a function that calls itself). Show
What is recursion?Recursion is the process of defining something in terms of itself. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively. Python Recursive FunctionIn Python, we know that a function can call other functions. It is even possible for the function to call itself. These types of construct are termed as recursive functions. The following image shows the working of a recursive function called Following is an example of a recursive function to find the factorial of an integer. Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Example of a recursive function
Output The factorial of 3 is 6 In the above example, When we call this function with a positive integer, it will recursively call itself by decreasing the number. Each function multiplies the number with the factorial of the number below it until it is equal to one. This recursive call can be explained in the following steps. factorial(3) # 1st call with 3 3 * factorial(2) # 2nd call with 2 3 * 2 * factorial(1) # 3rd call with 1 3 * 2 * 1 # return from 3rd call as number=1 3 * 2 # return from 2nd call 6 # return from 1st call Let's look at an image that shows a step-by-step process of what is going on: Working of a recursive factorial functionOur recursion ends when the number reduces to 1. This is called the base condition. Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely. The Python interpreter limits the depths of recursion to help avoid infinite recursions, resulting in stack overflows. By default, the maximum depth of recursion is 1000. If the limit is crossed, it results in
Output Traceback (most recent call last): File " Advantages of Recursion
Disadvantages of Recursion
If you’re familiar with functions in Python, then you know that it’s quite common for one function to call another. In Python, it’s also possible for a function to call itself! A function that calls itself is said to be recursive, and the technique of employing a recursive function is called recursion. It may seem peculiar for a function to call itself, but many types of programming problems are best expressed recursively. When you bump up against such a problem, recursion is an indispensable tool for you to have in your toolkit. By the end of this tutorial, you’ll understand:
Then you’ll study several Python programming problems that use recursion and contrast the recursive solution with a comparable non-recursive one. What Is Recursion?The word recursion comes from the Latin word recurrere, meaning to run or hasten back, return, revert, or recur. Here are some online definitions of recursion:
A recursive definition is one in which the defined term appears in the definition itself. Self-referential situations often crop up in real life, even if they aren’t immediately recognizable as such. For example, suppose you wanted to describe the set of people that make up your ancestors. You could describe them this way: Notice how the concept that is being defined, ancestors, shows up in its own definition. This is a recursive definition. In programming, recursion has a very precise meaning. It refers to a coding technique in which a function calls itself. Why Use Recursion?Most programming problems are solvable without recursion. So, strictly speaking, recursion usually isn’t necessary. However, some situations particularly lend themselves to a self-referential definition—for example, the definition of ancestors shown above. If you were devising an algorithm to handle such a case programmatically, a recursive solution would likely be cleaner and more concise. Traversal of tree-like data structures is another good example. Because these are nested structures, they readily fit a recursive definition. A non-recursive algorithm to walk through a nested structure is likely to be somewhat clunky, while a recursive solution will be relatively elegant. An example of this appears later in this tutorial. On the other hand, recursion isn’t for every situation. Here are some other factors to consider:
Typically, the readability of the code will be the biggest determining factor. But it depends on the circumstances. The examples presented below should help you get a feel for when you should choose recursion. Recursion in PythonWhen you call a function in Python, the interpreter creates a new local namespace so that names defined within that function don’t collide with identical names defined elsewhere. One function can call another, and even if they both define objects with the same name, it all works out fine because those objects exist in separate namespaces. The same holds true if multiple instances of the same function are running concurrently. For example, consider the following definition:
When Unfortunately, running >>>
As written, Python doesn’t allow that to happen. The interpreter limits the maximum number of times a function can call itself recursively, and when it reaches that limit, it raises a There isn’t much use for a function to indiscriminately call itself recursively without end. It’s reminiscent of the instructions that you sometimes find on shampoo bottles: “Lather, rinse, repeat.” If you were to follow these instructions literally, you’d shampoo your hair forever! This logical flaw has evidently occurred to some shampoo manufacturers, because some shampoo bottles instead say “Lather, rinse, repeat as necessary.” That provides a termination condition to the instructions. Presumably, you’ll eventually feel your hair is sufficiently clean to consider additional repetitions unnecessary. Shampooing can then stop. Similarly, a function that calls itself recursively must have a plan to eventually stop. Recursive functions typically follow this pattern:
You’re now ready to see how this works with some examples. Get Started: Count Down to ZeroThe first example is a function called >>>
Notice how
The version of
Here’s one possible non-recursive implementation for comparison: >>>
This is a case where the non-recursive solution is at least as clear and intuitive as the recursive one, and probably more so. Calculate FactorialThe next example involves the mathematical concept of factorial. The factorial of a positive integer n, denoted as n!, is defined as follows: In other words, n! is the product of all integers from 1 to n, inclusive. Factorial so lends itself to recursive definition that programming texts nearly always include it as one of the first examples. You can express the definition of n! recursively like this: As with the example shown above, there are base cases that are solvable without recursion. The more complicated cases are reductive, meaning that they reduce to one of the base cases:
For example, recursive computation of 4! looks like this: Recursive Calculation of 4!The calculations of 4!, 3!, and 2! suspend until the algorithm reaches the base case where n = 1. At that point, 1! is computable without further recursion, and the deferred calculations run to completion. Define a Python Factorial FunctionHere’s a recursive Python function to calculate factorial. Note how concise it is and how well it mirrors the definition shown above: >>>
A little embellishment of this function with some
>>>
Notice how all the recursive calls stack up. The function gets called with Recursion isn’t necessary here. You could implement >>>
You can also implement factorial using Python’s
>>>
Again, this shows that if a problem is solvable with recursion, there will also likely be several viable non-recursive solutions as well. You’ll typically choose based on which one results in the most readable and intuitive code. Another factor to take into consideration is execution speed. There can be significant performance differences between recursive and non-recursive solutions. In the next section, you’ll explore these differences a little further. Speed Comparison of Factorial ImplementationsTo evaluate execution time, you can use a function called
>>>
Here, the The examples shown below use First, here’s the recursive version: >>>
Next up is the iterative implementation: >>>
Last, here’s the version that uses >>>
In this case, the iterative implementation is the fastest, although the recursive solution isn’t far behind. The method using Does it matter? There’s a difference of almost four seconds in execution time between the iterative
implementation and the one that uses If you’ll be calling a function many times, you might need to take execution speed into account when choosing an implementation. On the other hand, if the function will run relatively infrequently, then the difference in execution times will probably be negligible. In that case, you’d be better off choosing the implementation that seems to express the solution to the problem most clearly. For factorial, the timings recorded above suggest a recursive implementation is a reasonable choice. Frankly, if you’re coding in Python, you don’t need to implement a factorial function at all. It’s already available in the standard >>>
Perhaps it might interest you to know how this performs in the timing test: >>>
Wow! A function implemented in C will virtually always be faster than a corresponding function implemented in pure Python. Traverse a Nested ListThe next example involves visiting each item in a nested list structure. Consider the following Python list:
As the following diagram shows, Suppose you wanted to count the number of leaf elements in this list—the lowest-level Just calling
>>>
What you need here is a function that traverses the entire list structure, sublists included. The algorithm goes something like this:
Note the self-referential nature of this description: Walk through the list. If you encounter a sublist, then similarly walk through that list. This situation begs for recursion! Traverse a Nested List RecursivelyRecursion fits this problem very nicely. To solve it, you need to be able to determine whether a given list item is leaf item or not. For that, you
can use the built-in Python function In the case of the >>>
Now you have the tools in place to implement a function that counts leaf elements in a list, accounting for sublists recursively:
If you run >>>
As with the factorial example, adding some
Here’s a synopsis of what’s happening in the example above:
The output from >>>
Each time a call to Traverse a Nested List Non-RecursivelyLike the other examples shown so far, this list traversal doesn’t require recursion. You can also accomplish it iteratively. Here’s one possibility:
If you run this non-recursive version of >>>
The strategy employed here uses a stack to handle the nested sublists. When this version of In fact, essentially the same thing happens in the recursive implementation as well. When you call a function recursively, Python saves the state of the executing instance on a stack so the recursive call can run. When the recursive call finishes, the state is popped from the stack so that the interrupted instance can resume. It’s the same concept, but with the recursive solution, Python is doing the state-saving work for you. Notice how concise and readable the recursive code is when compared to the non-recursive version: Recursive vs Non-Recursive Nested List TraversalThis is a case where using recursion is definitely an advantage. Detect PalindromesThe choice of whether to use recursion to solve a problem depends in large part on the nature of the problem. Factorial, for example, naturally translates to a recursive implementation, but the iterative solution is quite straightforward as well. In that case, it’s arguably a toss-up. The list traversal problem is a different story. In that case, the recursive solution is very elegant, while the non-recursive one is cumbersome at best. For the next problem, using recursion is arguably silly. A palindrome is a word that reads the same backward as it does forward. Examples include the following words:
If asked to devise an algorithm to determine whether a string is palindromic, you would probably come up with something like “Reverse the string and see if it’s the same as the original.” You can’t get much plainer than that. Even more helpfully, Python’s >>>
This is clear and concise. There’s hardly any need to look for an alternative. But just for fun, consider this recursive definition of a palindrome:
Slicing is your friend here as well. For a string
So you can define >>>
It’s an interesting exercise to think recursively, even when it isn’t especially necessary. Sort With QuicksortThe final example presented, like the nested list traversal, is a good example of a problem that very naturally suggests a recursive approach. The Quicksort algorithm is an efficient sorting algorithm developed by British computer scientist Tony Hoare in 1959. Quicksort is a divide-and-conquer algorithm. Suppose you have a list of objects to sort. You start by choosing an item in the list, called the pivot item. This can be any item in the list. You then partition the list into two sublists based on the pivot item and recursively sort the sublists. The steps of the algorithm are as follows:
Each partitioning produces smaller sublists, so the algorithm is reductive. The base cases occur when the sublists are either empty or have one element, as these are inherently sorted. Choosing the Pivot ItemThe Quicksort algorithm will work no matter what item in the list is the pivot item. But some choices are better than others. Remember that when partitioning, two sublists that are created: one with items that are less than the pivot item and one with items that are greater than the pivot item. Ideally, the two sublists are of roughly equal length. Imagine that your initial list to sort contains eight items. If each partitioning results in sublists of roughly equal length, then you can reach the base cases in three steps: Optimal Partitioning, Eight-Item ListAt the other end of the spectrum, if your choice of pivot item is especially unlucky, each partition results in one sublist that contains all the original items except the pivot item and another sublist that is empty. In that case, it takes seven steps to reduce the list to the base cases: Suboptimal Partitioning, Eight-Item ListThe Quicksort algorithm will be more efficient in the first case. But you’d need to know something in advance about the nature of the data you’re sorting in order to systematically choose optimal pivot items. In any case, there isn’t any one choice that will be the best for all cases. So if you’re writing a Quicksort function to handle the general case, the choice of pivot item is somewhat arbitrary. The first item in the list is a common choice, as is the last item. These will work fine if the data in the list is fairly randomly distributed. However, if the data is already sorted, or even nearly so, then these will result in suboptimal partitioning like that shown above. To avoid this, some Quicksort algorithms choose the middle item in the list as the pivot item. Another option is to find the median of the first, last, and middle items in the list and use that as the pivot item. This is the strategy used in the sample code below. Implementing the PartitioningOnce you’ve chosen the pivot item, the next step is to partition the list. Again, the goal is to create two sublists, one containing the items that are less than the pivot item and the other containing those that are greater. You could accomplish this directly in place. In other words, by swapping items, you could shuffle the items in the list around until the pivot item is in the middle, all the lesser items are to its left, and all the greater items are to its right. Then, when you Quicksort the sublists recursively, you’d pass the slices of the list to the left and right of the pivot item. Alternately, you can use Python’s list manipulation capability to create new lists instead of operating on the original list in place. This is the approach taken in the code below. The algorithm is as follows:
Note that this involves creating a third sublist that contains the pivot item itself. One advantage to this approach is that it smoothly handles the case where the pivot item appears in the list more than once. In that case, list 2 will have more than one element. Using the Quicksort ImplementationNow that the groundwork is in place, you are ready to move on to the Quicksort algorithm. Here’s the Python code:
This is what each section of
Here are some examples of >>>
For testing purposes, you can define a short function that generates a list of random numbers between
Now you can use >>>
To further understand how In the first step, the first, middle, and last list values are
Each sublist is subsequently partitioned recursively in the same manner until all the sublists either contain a single element or are empty. As the recursive calls return, the lists are reassembled in sorted order. Note that in the second-to-last step on the left, the pivot item ConclusionThat concludes your journey through recursion, a programming technique in which a function calls itself. Recursion isn’t by any means appropriate for every task. But some programming problems virtually cry out for it. In those situations, it’s a great technique to have at your disposal. In this tutorial, you learned:
You also saw several examples of recursive algorithms and compared them to corresponding non-recursive solutions. You should now be in a good position to recognize when recursion is called for and be ready to use it confidently when it’s needed! If you want to explore more about recursion in Python, then check out Thinking Recursively in Python. What is recursive function in python?Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
What is called recursive?Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.
What is recursive function in python Mcq?Explanation: The appropriate definition for a recursive function is a function execution instance that calls another execution instance of the same function either directly or indirectly.
How do you define a recursive function?Recursive Function is a function that repeats or uses its own previous term to calculate subsequent terms and thus forms a sequence of terms. Usually, we learn about this function based on the arithmetic-geometric sequence, which has terms with a common difference between them.
|