Python recursive function examples

Table of contents

Recursive exponential

Given two exponential numbers with the same base, the multiplication is another exponential number with the same base but we add the exponents. We can utilize this observation and define a recursive exponential formula. If (n) is even number, return the square of x^(n/2) because

otherwise, return (x) multiplied by x^(n-1) because

and the base case when (n) is either 0 or 1

Implementation

Here is the implementation in Python…

If you run the code above you should get the output below…

Recursive max

Write a recursive function to find the maximum value element in an Array of size N.

Algorithm

One way to do that is to split the array into two halves then find the largest number in each portion then return the largest of the two. Please note that as we divide the array into halves we are actually copying data instead of operating in place.

Implementation

The following is a suggested solution in Python…

If you run the code above, you should get the output below…

Recursive multiplication

Write a Python recursive function to compute the product of two positive integers.

Algorithm

The product of two positive integers (A*B) is nothing but the sum of the first integer (A), (B) times

Implementation

Here is the code in Python…

If you think about the code above, it is not recursive naturally but iterative. What we are doing actually is performing iteration using recursion which is a weird way to do it.

Recursive sum

Write a recursive function to find the sum of all elements in an Array.

Algorithm

If the array is only one element then return that element otherwise return the first element added to all elements that come after.

Implementation

The following is a suggested solution in Python…

If you run the code above, you should get the output below…

Recursive average

We are going to calculate the average in a similar way to sum. Note that…

The only difference is that we divide by (n). Here is an implementation in Python…

Implementation

If you run the code snippet above you should get

Recursive uppercase

Write a recursive function to convert a string to uppercase

Algorithm

As we indicated earlier, this is also not recursive naturally but iterative. What we are doing actually is performing iteration using recursion

Implementation

Here is an example Python implementation…

Thanks for visiting. For questions and feedback please use the comments section below.

Add a Comment

Your email address will not be published. Required fields are marked *