Author name: Vikram Chiluka

Program to Find the LCM of Two Numbers Using Recursion

Python Program to Find the LCM of Two Numbers Using Recursion

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Recursion:

Recursion is a functional technique to problem-solving that involves breaking an issue down into a series of small subproblems with an identical pattern and solving them sequentially by calling one subproblem within another. Recursion is carried out by defining a function capable of solving one subproblem at a time. It calls itself but solves another subproblem somewhere inside that method. As a result, the call to itself continues until some limiting requirements are met.

The main program’s first call to a recursive function will be returned only after all sub calls have completed. As a result, Python keeps the results of all subproblems in temporary memory, does some arithmetic operations (if necessary), and releases the memory at the end of the recursion.

The smallest positive number that is divisible by both a and b is the least or lowest common multiple (LCM) of two numbers a and b. In this article, we’ll look at how to use recursion to find the LCM of two numbers.

Examples:

Example1:

Input:

given first number = 10
given second number = 16

Output:

The value of lcm of the given two numbers 10 16  =  80

Example2:

Input:

given first number = 10
given second number = 16

Output:

The value of lcm of the given two numbers 5 17  =  85

Program to Find the LCM of Two Numbers Using Recursion in Python

There are several ways to calculate the lcm of the given two numbers using recursion some of them are:

Method #1:Using Recursion (Static Input)

Approach:

  • Give two numbers as static input and store them in two variables.
  • Pass the given two numbers as arguments to the recursive function which calculates the lcm of the given two numbers.
  • Set the multiple variable to the highest value between the given two numbers.
  • Check to see if the multiple variable  divides both given numbers perfectly.
  • If it does, the process is terminated and the multiple variable is returned as the LCM.
  • If the multiple does not divide both given numbers perfectly, then it is increased by the maximum value among both given numbers using the max() function.
  • The recursive function returns the multiple variable which is the result(lcm of the given two numbers)
  • Print the LCM of the given two numbers.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the given two numbers as arguments
# and return the lcm of the given two numbers.


def lcmRecursion(numb1, numb2):
    # Set the multiple variable to the highest value between the given two numbers.
    lcmRecursion.multiple = lcmRecursion.multiple+numb2
    # Check to see if the multiple variable  divides both given numbers perfectly.
    if((lcmRecursion.multiple % numb1 == 0) and (lcmRecursion.multiple % numb2 == 0)):
      # If it does, the process is terminated and the multiple variable is returned as the LCM.
        return lcmRecursion.multiple
    else:
      # If the multiple does not divide both given numbers perfectly, then it is increased by the maximum value
      # among both given numbers using the max() function.
        lcmRecursion(numb1, numb2)
    # The recursive function returns the multiple variable
    # which is the result(lcm of the given two numbers)
    return lcmRecursion.multiple


# set multiplee variable value to 0
lcmRecursion.multiple = 0
# Give two numbers as static input and store them in two variables.
numbe1 = 10
numbe2 = 16
# if the first number is greater than second number then swap the arguments
if(numbe1 > numbe2):
    LcmVal = lcmRecursion(numbe2, numbe1)
# else pass the original numbers as arguments
else:
    LcmVal = lcmRecursion(numbe1, numbe2)
print('The value of lcm of the given two numbers', numbe1, numbe2, ' = ', LcmVal)

Output:

The value of lcm of the given two numbers 10 16  =  80

Explanation:

  • The two numbers are given as static input.
  • The multiple variable is set to the highest value between the given two numbers.
  • The multiple variable is tested to see if it divides the given two numbers perfectly.
  • If so, the procedure is terminated and the multiple is returned as the LCM.
  • If the multiple variable does not divide the given two numbers perfectly, the multiple variable is returned by the maximum value among both given numbers.
  • The variable with multiple values is returned, and the LCM of the two variables is printed.

Method #2:Using Recursion (User Input separated by space)

Approach:

  • Scan the given two numbers as user input using a map, int, and split() functions and store them in two variables.
  • Pass the given two numbers as arguments to the recursive function which calculates the lcm of the given two numbers.
  • Set the multiple variable to the highest value between the given two numbers.
  • Check to see if the multiple variable divides both given numbers perfectly.
  • If it does, the process is terminated and the multiple variable is returned as the LCM.
  • If the multiple does not divide both given numbers perfectly, then it is increased by the maximum value among both given numbers using the max() function.
  • The recursive function returns the multiple variable which is the result(lcm of the given two numbers)
  • Print the LCM of the given two numbers.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the given two numbers as arguments
# and return the lcm of the given two numbers.


def lcmRecursion(numb1, numb2):
    # Set the multiple variable to the highest value between the given two numbers.
    lcmRecursion.multiple = lcmRecursion.multiple+numb2
    # Check to see if the multiple variable  divides both given numbers perfectly.
    if((lcmRecursion.multiple % numb1 == 0) and (lcmRecursion.multiple % numb2 == 0)):
      # If it does, the process is terminated and the multiple variable is returned as the LCM.
        return lcmRecursion.multiple
    else:
      # If the multiple does not divide both given numbers perfectly, then it is increased by the maximum value
      # among both given numbers using the max() function.
        lcmRecursion(numb1, numb2)
    # The recursive function returns the multiple variable
    # which is the result(lcm of the given two numbers)
    return lcmRecursion.multiple


# set multiplee variable value to 0
lcmRecursion.multiple = 0
# Scan the given two numbers as user input using a map,
# int, and split() functions and store them in two variables.
numbe1, numbe2 = map(int, input(
    'Enter two random numbers separated by space =').split())
# if the first number is greater than second number then swap the arguments
if(numbe1 > numbe2):
    LcmVal = lcmRecursion(numbe2, numbe1)
# else pass the original numbers as arguments
else:
    LcmVal = lcmRecursion(numbe1, numbe2)
print('The value of lcm of the given two numbers', numbe1, numbe2, ' = ', LcmVal)

Output:

Enter two random numbers separated by space =5 17
The value of lcm of the given two numbers 5 17 = 85

Explanation:

Here the map function converts the given two numbers from string to integer data type and the split() function
splits the given two numbers by space.

Method #3:Using Recursion (User Input separated by newline)

Approach:

  • Scan the first number as user input using the int(input()) function and store it in a  variable.
  • Scan the second number as user input using the int(input()) function and store it in another variable.
  • Here int() is used to convert the given number to integer datatype.
  • Pass the given two numbers as arguments to the recursive function which calculates the lcm of the given two numbers.
  • Set the multiple variable to the highest value between the given two numbers.
  • Check to see if the multiple variable divides both given numbers perfectly.
  • If it does, the process is terminated and the multiple variable is returned as the LCM.
  • If the multiple does not divide both given numbers perfectly, then it is increased by the maximum value among both given numbers using the max() function.
  • The recursive function returns the multiple variable which is the result(lcm of the given two numbers)
  • Print the LCM of the given two numbers.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the given two numbers as arguments
# and return the lcm of the given two numbers.


def lcmRecursion(numb1, numb2):
    # Set the multiple variable to the highest value between the given two numbers.
    lcmRecursion.multiple = lcmRecursion.multiple+numb2
    # Check to see if the multiple variable  divides both given numbers perfectly.
    if((lcmRecursion.multiple % numb1 == 0) and (lcmRecursion.multiple % numb2 == 0)):
      # If it does, the process is terminated and the multiple variable is returned as the LCM.
        return lcmRecursion.multiple
    else:
      # If the multiple does not divide both given numbers perfectly, then it is increased by the maximum value
      # among both given numbers using the max() function.
        lcmRecursion(numb1, numb2)
    # The recursive function returns the multiple variable
    # which is the result(lcm of the given two numbers)
    return lcmRecursion.multiple


# set multiplee variable value to 0
lcmRecursion.multiple = 0
# Scan the first number as user input using the int(input())
# function and store it in a  variable.
numbe1 = int(input('Enter some random number = '))
# Scan the second number as user input using the int(input())
# function and store it in another variable.
# Here int() is used to convert the given number to integer datatype.
numbe2=int(input('Enter some random number = '))
# if the first number is greater than second number then swap the arguments
if(numbe1 > numbe2):
    LcmVal=lcmRecursion(numbe2, numbe1)
# else pass the original numbers as arguments
else:
    LcmVal=lcmRecursion(numbe1, numbe2)
print('The value of lcm of the given two numbers', numbe1, numbe2, ' = ', LcmVal)

Output:

Enter some random number = 9
Enter some random number = 3
The value of lcm of the given two numbers 9 3 = 9

Related Programs:

Python Program to Find the LCM of Two Numbers Using Recursion Read More »

Program to Find if a Number is Prime or Not Prime Using Recursion

Python Program to Find if a Number is Prime or Not Prime Using Recursion

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Recursion in Python:

When a function calls itself and loops until it reaches the intended end state, this is referred to as recursion. It is based on the mathematics idea of recursive definitions, which define elements in a set in terms of other members in the set.

Each recursive implementation contains a base case in which the desired state is reached, and a recursive case in which the desired state is not reached and the function enters another recursive phase.

On each step, the behavior in the recursive situation prior to the recursive function call, the internal self-call, is repeated. Recursive structures are beneficial when a larger problem (the base case) can be solved by solving repeated subproblems (the recursive case) that incrementally advance the program to the base case.
It behaves similarly to for and while loops, with the exception that recursion moves closer to the desired condition, whereas for loops run a defined number of times and while loops run until the condition is no longer met.

In other words, recursion is declarative because you specify the desired state, whereas for/while loops are iterative because you provide the number of repeats.

Examples:

Example1:

Input:

given number  = 97

Output:

The given number 97 is prime number.

Example2:

Input:

given number  = 139

Output:

The given number 139 is a prime number.

Program to Find if a Number is Prime or Not Prime Using Recursion in Python

Using recursion, the program takes a number and determines whether or not it is prime.

If a number is only divided by itself and one, it is said to be prime.

So we iterate from 2 to n-1, returning False if n is divisible by any of (2,3,4,…n-1).

In addition, we look for other factors or divisors of the number, and if the remainder is zero, we know the number has factors and is not prime.

Also, if j==n, then there is no number from (2,3,4,…n-1) that is divisible by n, implying that it is prime.

Below are the ways to Find if a Number is Prime or Not Prime using the recursive approach in Python:

1)Using Recursion(Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Pass the number to a recursive function as an argument, and set the divisor count to NULL.
  • The number’s divisors are then checked via recursion, and either True or False is returned.
  • If the function returns true then it is a prime number.
  • Else it is not a prime number.
  • The exit of the program.

Below is the implementation:

def checkPrimeRecursion(numb, divisors=None):
    if divisors is None:
        divisors = numb - 1
    while divisors >= 2:
        if numb % divisors == 0:
            # if we find the divisor then return false because it is not prime
            return False
        else:
            return checkPrimeRecursion(numb, divisors-1)
    else:
      # if we reach here return true because we did not find any
      # divisors of the given number
        return True


# Give the number as static input and store it in a variable.
given_numb = 97
# passing the given number as argument to the recursive function checkPrimeRecursion.
# If the function returns true then it is a prime number.
if(checkPrimeRecursion(given_numb)):
    print('The given number', given_numb, 'is a prime number.')
# Else it is not a prime number.
else:
    print('The given number', given_numb, 'is not a prime number.')

Output:

The given number 97 is prime number.

2)Using Recursion(User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Pass the number to a recursive function as an argument, and set the divisor count to NULL.
  • The number’s divisors are then checked via recursion, and either True or False is returned.
  • If the function returns true then it is a prime number.
  • Else it is not a prime number.
  • The exit of the program.

Below is the implementation:

def checkPrimeRecursion(numb, divisors=None):
    if divisors is None:
        divisors = numb - 1
    while divisors >= 2:
        if numb % divisors == 0:
            # if we find the divisor then return false because it is not prime
            return False
        else:
            return checkPrimeRecursion(numb, divisors-1)
    else:
      # if we reach here return true because we did not find any
      # divisors of the given number
        return True


# Give the number as user input using the int(input()) function and store it in a variable.
given_numb = int(input('Enter some random number = '))
# passing the given number as argument to the recursive function checkPrimeRecursion.
# If the function returns true then it is a prime number.
if(checkPrimeRecursion(given_numb)):
    print('The given number', given_numb, 'is a prime number.')
# Else it is not a prime number.
else:
    print('The given number', given_numb, 'is not a prime number.')

Output:

Enter some random number = 139
The given number 139 is a prime number.

Related Programs:

Python Program to Find if a Number is Prime or Not Prime Using Recursion Read More »

Python Program to Calculate Sum of Nth Power using Recursion

Python Program to Calculate Sum of Nth Power using Recursion

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Find the number of ways a given integer can be represented as the sum of the Nth power of the unique, natural integers using this program. For example, if X = 100 and N = 2, we must identify all square combinations that add up to 100. The potential solutions are (10,2), (8^2+6^2), (1^2+3^2+4^2+5^2+7^2). As a result, the total number of solutions is three.

Examples:

Example1:

Input:

Given number = 25

Given N =2

Output:

The possible solutions count = 2

Example2:

Input:

Given number = 100
Given N =2

Output:

The possible solutions count = 3

Python Program to Calculate Sum of Nth Power using Recursion

Below are the ways to write a program that calculates the sum of Nth  Power using Recursion.

Method #1: Using Recursion (Static Input)

Approach:

  • Give the number and N as static input and store them in two separate variables.
  • Create a function countNPower() function which returns the total number of possible solutions count.
  • Pass the given number and N,1 as arguments to the countNPower() function.
  • Check to see if the number equals 1 power N, if so, there is only one potential/possible solution.
  • There is no solution if the number is smaller than 1 power of N.
  • If number is more than 1 power N, then countNPower(value, N, num+1)+countNPower(number, N, num+1) is returned.
  • The first countNPowercall includes the 1 power N value, but the second one excludes it.
  • Print the Result.
  • The Exit of the Program.

Below is the implementation:

# Create a function countNPower() function which
# returns the total number of possible solutions count.


def countNPower(Number, n, numb):
    resultval = Number-pow(numb, n)
    # There is no solution if the number is smaller than 1 power of N.
    if resultval < 0:
        return 0
    # Check to see if the number equals 1 power N,
    # if so, there is only one potential/possible solution.
    elif resultval == 0:
        return 1
    # If number is more than 1 power N, then
    # countNPower(value, N, num+1)+countNPower(number, N, num+1) is returned.
    # The first countNPowercall includes the 1 power N value,
    # but the second one excludes it.
    else:
        return countNPower(resultval, n, numb+1)+countNPower(Number, n, numb+1)


# Give the number and N as static input and store them in two separate variables.
Numb = 25
n = 2
# Pass the given number and N,1 as arguments to the countNPower() function.
print('The possible solutions count = ', countNPower(Numb, n, 1))

Output:

The possible solutions count =  2

Method #2: Using Recursion (User Input)

Approach:

  • Give the number and N as user input using map(),split(), and input() functions.
  • Store them in two separate variables.
  • Create a function countNPower() function which returns the total number of possible solutions count.
  • Pass the given number and N,1 as arguments to the countNPower() function.
  • Check to see if the number equals 1 power N, if so, there is only one potential/possible solution.
  • There is no solution if the number is smaller than 1 power of N.
  • If number is more than 1 power N, then countNPower(value, N, num+1)+countNPower(number, N, num+1) is returned.
  • The first countNPowercall includes the 1 power N value, but the second one excludes it.
  • Print the Result.
  • The Exit of the Program.

Below is the implementation:

# Create a function countNPower() function which
# returns the total number of possible solutions count.


def countNPower(Number, n, numb):
    resultval = Number-pow(numb, n)
    # There is no solution if the number is smaller than 1 power of N.
    if resultval < 0:
        return 0
    # Check to see if the number equals 1 power N,
    # if so, there is only one potential/possible solution.
    elif resultval == 0:
        return 1
    # If number is more than 1 power N, then
    # countNPower(value, N, num+1)+countNPower(number, N, num+1) is returned.
    # The first countNPowercall includes the 1 power N value,
    # but the second one excludes it.
    else:
        return countNPower(resultval, n, numb+1)+countNPower(Number, n, numb+1)


# Give the number and N as user input using map(),split(), and input() functions.
# Store them in two separate variables.
Numb, n = map(int, input(
    'Enter some random number and N separated by spaces = ').split())
# Pass the given number and N,1 as arguments to the countNPower() function.
print('The possible solutions count = ', countNPower(Numb, n, 1))

Output:

Enter some random number and N separated by spaces = 100 2
The possible solutions count = 3

Related Programs:

Python Program to Calculate Sum of Nth Power using Recursion Read More »

Program to Find the Length of a List Using Recursion

Python Program to Find the Length of a List Using Recursion

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Recursion:

Recursion is a functional technique to problem-solving that involves breaking an issue down into a series of small subproblems with an identical pattern and solving them sequentially by calling one subproblem within another. Recursion is carried out by defining a function capable of solving one subproblem at a time. It calls itself but solves another subproblem somewhere inside that method. As a result, the call to itself continues until some limiting requirements are met.

The main program’s first call to a recursive function will be returned only after all sub calls have completed. As a result, Python keeps the results of all subproblems in temporary memory, does some arithmetic operations (if necessary), and releases the memory at the end of the recursion.

Lists in Python:

A list is a built-in Python data structure that stores a collection of things. Lists have a number of key features:

  • Items in a list are enclosed in square brackets, as in [item1, item2, item3].
  • Lists are ordered, which means that the items in the list appear in a particular order. This allows us to use an index to find any object.
  • Lists are mutable, which means they can be added or removed once they are created.
  • List elements do not have to be distinct. Item duplication is possible since each element has its own individual address and may be accessed independently via the index.
  • Elements can be of many data types: strings, numbers, and objects can all be combined in the same list.

Given a list, the task is to calculate the length of the given list recursively in Python

Examples:

Example1:

Input:

given list = [929, 138, 3, 193, 11, 1, 2, 3, 41, 132, 56, 11, 917, 212, 455, 2235, 1, 1, 2, 3]

Output:

The given list is :
[929, 138, 3, 193, 11, 1, 2, 3, 41, 132, 56, 11, 917, 212, 455, 2235, 1, 1, 2, 3]
The length of the given list =  20

Example2:

Input:

given list = ['hello', 'this', 'btechgeeks', 'python']

Output:

The given list is :
['hello', 'this', 'btechgeeks', 'python']
The length of the given list =  4

Program to Find the Length of a List Using Recursion in Python

Below are the ways to find the length of the given list in python using the recursive approach:

When it is necessary to find the length of a list using recursion, a user-defined algorithm and a simple indexing method are utilized.
The recursion computes the output of little pieces of the larger problem and combines them to produce the answer to the larger problem.

1)Using Recursion(Static Input)

Approach:

  • Give the list input as static input and store it in a variable.
  • Pass the given list as an argument to the recursive function which calculates the length of the given list and returns it.
  • Put a condition in the method that says if it isn’t the original list, it should return 0.
  • Otherwise, execute the function recursively to determine the length of the list.
  • The Recursive function returns the length of the list.
  • Print the length of the given list.
  • The exit of Program.

Below is the implementation:

# function which accepts the list as argument and
# calculates the length of the given list and return it


def listlengthRecursion(given_list):
  # Put a condition in the method that says if it
  # isn't the original list, it should return 0.
    if not given_list:
        return 0
    # Otherwise, execute the function recursively to determine the length of the list.
    return 1 + listlengthRecursion(given_list[1::2]) + listlengthRecursion(given_list[2::2])


# Give the list input as static input and store it in a variable.
given_list = [929, 138, 3, 193, 11, 1, 2, 3, 41,
              132, 56, 11, 917, 212, 455, 2235, 1, 1, 2, 3]
# printing the given list
print('The given list is :')
print(given_list)
# Pass the given list as an argument to the recursive function which
# calculates the length of the given list and returns it.
print("The length of the given list = ", listlengthRecursion(given_list))

Output:

The given list is :
[929, 138, 3, 193, 11, 1, 2, 3, 41, 132, 56, 11, 917, 212, 455, 2235, 1, 1, 2, 3]
The length of the given list =  20

Explanation:

  • Create a recursive function that accepts a list as an argument.
  • Given the list input as static input and stored it into a variable.
  • Put a condition in the method that says if it isn’t the original list, it should return 0.
  • Otherwise, execute the function recursively to determine the length of the list.
  • Print the result(which is the length of the given list)

2)Using Recursion(User Input)

i)Integer List

Approach:

  • Give the list as user input (integer list) using the map(),int(),split() and list() functions and store in a variable.
  • Pass the given list as an argument to the recursive function which calculates the length of the given list and returns it.
  • Put a condition in the method that says if it isn’t the original list, it should return 0.
  • Otherwise, execute the function recursively to determine the length of the list.
  • The Recursive function returns the length of the list.
  • Print the length of the given list.
  • The exit of Program.

Below is the implementation:

# function which accepts the list as argument and
# calculates the length of the given list and return it


def listlengthRecursion(given_list):
  # Put a condition in the method that says if it
  # isn't the original list, it should return 0.
    if not given_list:
        return 0
    # Otherwise, execute the function recursively to determine the length of the list.
    return 1 + listlengthRecursion(given_list[1::2]) + listlengthRecursion(given_list[2::2])


# Give the list as user input (integer list) using the map(),int(),split() and list()
# functions and store in a variable.
given_list = list(map(int, input('Enter some random elements of the list separated by spaces ').split()))
# printing the given list
print('The given list is :')
print(given_list)
# Pass the given list as an argument to the recursive function which
# calculates the length of the given list and returns it.
print("The length of the given list = ", listlengthRecursion(given_list))

Output:

Enter some random elements of the list separated by spaces 7 372 1 93 2 491 22 434 11 45 9 8 2 3 4
The given list is :
[7, 372, 1, 93, 2, 491, 22, 434, 11, 45, 9, 8, 2, 3, 4]
The length of the given list = 15

ii)String List

Approach:

  • Give the list as user input (String list) using the split() and list() functions and store in a variable.
  • Pass the given list as an argument to the recursive function which calculates the length of the given list and returns it.
  • Put a condition in the method that says if it isn’t the original list, it should return 0.
  • Otherwise, execute the function recursively to determine the length of the list.
  • The Recursive function returns the length of the list.
  • Print the length of the given list.
  • The exit of Program.

Below is the implementation:

# function which accepts the list as argument and
# calculates the length of the given list and return it


def listlengthRecursion(given_list):
  # Put a condition in the method that says if it
  # isn't the original list, it should return 0.
    if not given_list:
        return 0
    # Otherwise, execute the function recursively to determine the length of the list.
    return 1 + listlengthRecursion(given_list[1::2]) + listlengthRecursion(given_list[2::2])


# Give the list as user input (String list) using the split() and list() functions and store in a variable.
given_list = list( input('Enter some random elements of the list separated by spaces =').split())
# printing the given list
print('The given list is :')
print(given_list)
# Pass the given list as an argument to the recursive function which
# calculates the length of the given list and returns it.
print("The length of the given list = ", listlengthRecursion(given_list))

Output:

Enter some random elements of the list separated by spaces =hello this is bychg btechgeeeks
The given list is :
['hello', 'this', 'is', 'bychg', 'btechgeeeks']
The length of the given list = 5

Related Programs:

Python Program to Find the Length of a List Using Recursion Read More »

Program to Generate Gray Codes using Recursion

Python Program to Generate Gray Codes using Recursion

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Recursive function:

In its definition, recursion is just calling the same function many times (this means, we are using that same function within its body).

Binary Code:

As previously stated, Binary Code is a Base-2 representation of a number. In Binary, all numbers are represented by simply two symbols: 0 and 1. Binary (also known as base-2) is a numerical system with only two digits: 0 and 1.

Gray Code:

A Gray Code is a method of encoding integers in which consecutive numbers differ by by one bit. Gray Code is created by arranging the binary numeral system in such a way that two consecutive values differ only by one bit.

The number of bits n has been specified. The task at hand is to generate n-bit Gray code. The Gray code is a binary number ordering in which two consecutive codewords differ by only one bit.

Examples:

Example1:

Input:

given number of bits = 5

Output:

Printing all 5 bits Gray Codes : 
['00000', '00001', '00011', '00010', '00110', '00111', '00101', '00100', '01100', '01101', '01111', '01110', '01010', 
'01011', '01001', '01000', '11000', '11001', '11011', '11010', '11110', '11111', '11101', '11100', '10100', '10101',
'10111', '10110', '10010', '10011', '10001', '10000']

Example2:

Input:

given number of bits = 7

Output:

Printing all 7 bits Gray Codes : 
['0000000', '0000001', '0000011', '0000010', '0000110', '0000111', '0000101', '0000100', '0001100', '0001101',
'0001111', '0001110', '0001010', '0001011', '0001001', '0001000', '0011000', '0011001', '0011011', '0011010',
'0011110', '0011111', '0011101', '0011100', '0010100', '0010101', '0010111', '0010110', '0010010', '0010011',
'0010001', '0010000', '0110000', '0110001', '0110011', '0110010', '0110110', '0110111', '0110101', '0110100',
'0111100', '0111101', '0111111', '0111110', '0111010', '0111011', '0111001', '0111000', '0101000', '0101001', 
'0101011', '0101010', '0101110', '0101111', '0101101', '0101100', '0100100', '0100101', '0100111', '0100110',
'0100010', '0100011', '0100001', '0100000', '1100000', '1100001', '1100011', '1100010', '1100110', '1100111',
'1100101', '1100100', '1101100', '1101101', '1101111', '1101110', '1101010', '1101011', '1101001', '1101000',
'1111000', '1111001', '1111011', '1111010', '1111110', '1111111', '1111101', '1111100', '1110100', '1110101',
'1110111', '1110110', '1110010', '1110011', '1110001', '1110000', '1010000', '1010001', '1010011', '1010010',
'1010110', '1010111', '1010101', '1010100', '1011100', '1011101', '1011111', '1011110', '1011010', '1011011',
'1011001', '1011000', '1001000', '1001001', '1001011', '1001010', '1001110', '1001111', '1001101', '1001100',
'1000100', '1000101', '1000111', '1000110', '1000010', '1000011', '1000001', '1000000']

Program to Generate Gray Codes using Recursion in Python

There are several ways to generate gray codes  using recursion some of them are:

Method #1:Using Recursion (Static Input)

Approach:

  • Give the value of numb as static input.
  • There is a function called printGrayCodes that is defined.
  • It accepts as an argument the number of bits n.
  • It returns a list of n-bit Gray codes.
  • To begin, the function obtains the (n – 1)-bit Gray code.
  • The first half of the n-bit Gray codewords are simply the (n – 1)-bit Gray codewords prefixed with a 0.
  • The second half of the n-bit Gray codewords is made up of (n – 1)-bit Gray codewords listed in reverse and prefixed with a 1.
  • The 0-bit Gray code is essentially the empty string.

Below is the implementation:

def printGrayCodes(numb):
    # Return a list of n-bit Gray codes.
    if numb == 0:
        return ['']
    # The first half of the n-bit Gray codewords are simply the (n – 1)-bit Gray
    # codewords prefixed with a 0.
    firstHalfBits = printGrayCodes(numb - 1)
    secondHalfBits = firstHalfBits.copy()
    # The second half of the n-bit Gray codewords is made up of (n – 1)-bit Gray codewords
    # listed in reverse and prefixed with a 1.
    firstHalfBits = ['0' + code for code in firstHalfBits]
    secondHalfBits = ['1' + code for code in reversed(secondHalfBits)]
    # printing the result
    return firstHalfBits + secondHalfBits


# Give the value of number of bits as static input
numb = 5
# passing the given number of bits to print gray codes
getOutput = printGrayCodes(numb)
print('Printing all', numb, 'bits', 'Gray Codes : ')
print(getOutput)

Output:

Printing all 5 bits Gray Codes : 
['00000', '00001', '00011', '00010', '00110', '00111', '00101', '00100', '01100', '01101', '01111', '01110', '01010', 
'01011', '01001', '01000', '11000', '11001', '11011', '11010', '11110', '11111', '11101', '11100', '10100', '10101',
 '10111', '10110', '10010', '10011', '10001', '10000']

Method #2:Using Recursion (User Input)

Approach:

  • Give some random number of bits as user input using int(input()) function.
  • There is a function called printGrayCodes that is defined.
  • It accepts as an argument the number of bits n.
  • It returns a list of n-bit Gray codes.
  • To begin, the function obtains the (n – 1)-bit Gray code.
  • The first half of the n-bit Gray codewords are simply the (n – 1)-bit Gray codewords prefixed with a 0.
  • The second half of the n-bit Gray codewords is made up of (n – 1)-bit Gray codewords listed in reverse and prefixed with a 1.
  • The 0-bit Gray code is essentially the empty string.

Below is the implementation:

def printGrayCodes(numb):
    # Return a list of n-bit Gray codes.
    if numb == 0:
        return ['']
    # The first half of the n-bit Gray codewords are simply the (n – 1)-bit Gray
    # codewords prefixed with a 0.
    firstHalfBits = printGrayCodes(numb - 1)
    secondHalfBits = firstHalfBits.copy()
    # The second half of the n-bit Gray codewords is made up of (n – 1)-bit Gray codewords
    # listed in reverse and prefixed with a 1.
    firstHalfBits = ['0' + code for code in firstHalfBits]
    secondHalfBits = ['1' + code for code in reversed(secondHalfBits)]
    # printing the result
    return firstHalfBits + secondHalfBits


# Give the value of number of bits as static input
numb = int(input('Enter some random number of bits = '))
# passing the given number of bits to print gray codes
getOutput = printGrayCodes(numb)
print('Printing all', numb, 'bits', 'Gray Codes : ')
print(getOutput)

Output:

Enter some random number of bits = 7
Printing all 7 bits Gray Codes : 
['0000000', '0000001', '0000011', '0000010', '0000110', '0000111', '0000101', '0000100', '0001100', '0001101',
 '0001111', '0001110', '0001010', '0001011', '0001001', '0001000', '0011000', '0011001', '0011011', '0011010',
 '0011110', '0011111', '0011101', '0011100', '0010100', '0010101', '0010111', '0010110', '0010010', '0010011',
 '0010001', '0010000', '0110000', '0110001', '0110011', '0110010', '0110110', '0110111', '0110101', '0110100',
 '0111100', '0111101', '0111111', '0111110', '0111010', '0111011', '0111001', '0111000', '0101000', '0101001', 
'0101011', '0101010', '0101110', '0101111', '0101101', '0101100', '0100100', '0100101', '0100111', '0100110',
 '0100010', '0100011', '0100001', '0100000', '1100000', '1100001', '1100011', '1100010', '1100110', '1100111',
 '1100101', '1100100', '1101100', '1101101', '1101111', '1101110', '1101010', '1101011', '1101001', '1101000',
 '1111000', '1111001', '1111011', '1111010', '1111110', '1111111', '1111101', '1111100', '1110100', '1110101',
 '1110111', '1110110', '1110010', '1110011', '1110001', '1110000', '1010000', '1010001', '1010011', '1010010',
 '1010110', '1010111', '1010101', '1010100', '1011100', '1011101', '1011111', '1011110', '1011010', '1011011',
 '1011001', '1011000', '1001000', '1001001', '1001011', '1001010', '1001110', '1001111', '1001101', '1001100',
 '1000100', '1000101', '1000111', '1000110', '1000010', '1000011', '1000001', '1000000']

Related Programs:

Python Program to Generate Gray Codes using Recursion Read More »

Program to Find the Total Sum of a Nested List Using Recursion

Python Program to Find the Total Sum of a Nested List Using Recursion

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Recursion in Python:

Python also supports function recursion, which means that a specified function can call itself.

Recursion is a mathematical and programming concept that is widely used. It signifies that a function calls itself. This has the advantage of allowing you to loop through data to obtain a result.

The developer must exercise extreme caution when using recursion since it is quite easy to write a function that never terminates or consumes excessive amounts of memory or computing power. However, when performed correctly, recursion may be a tremendously efficient and mathematically elegant way to programming.

Nested List:

A list can include any form of the object, including another list (sublist), which can contain sublists, and so on. This is referred to as a nested list.

Given a nested list, the task is to calculate the sum of the elements in the given list using recursion.

Examples:

Example1:

Input:

given nested list = [[7, 8, 2], [11, 19, 29, 63, 91], [12, 52, 98], [11, 19, 18], [11, 28, 34, 39, 35, 56, 87, 46, 1, 2], [5], [9, 23], [3, 23, 124]]

Output:

Printing the given nested list : 
 [[7, 8, 2], [11, 19, 29, 63, 91], [12, 52, 98], [11, 19, 18], [11, 28, 34, 39, 35, 56, 87, 46, 1, 2], [5], [9, 23], [3, 23, 124]]
The sum of all elements of the given nested list is : 966

Example2:

Input:

given Nested List = [[1, 7], [11, 28, 122], [99, 100, 11, 111]]

Output:

Printing the given nested list : 
 [[1, 7], [11, 28, 122], [99, 100, 11, 111]]
The sum of all elements of the given nested list is : 490

Program to Find the Total Sum of a Nested List Using Recursion in Python

Below is the full approach to calculate the total sum of all the elements in the given nested list using recursion in python.

Idea:

Iterate through the list, and if an element of the list is also a list, we must perform the same operation of calculating the total with this element list (which can be nested). So now that we’ve identified a subproblem, we can use the same method to complete the task by simply changing the argument to this sublist. If the element isn’t a list, just add its value to the global total.

Approach:

  • Give the nested list as static input and store it in a variable.
  • To find the total of the list’s elements, pass the list as an input to a recursive function say sumNestedListRecursion.
  • Taking a variable that stores the sum of the elements of a nested list
    and Initialize it with 0.
  • To get the elements inside the sublists, use a for loop and recursion in the function, and store the summed up elements in a variable.
  • The total sum of all the elements(integers) in the given nested list will be returned.
  • Print the total sum of all the elements in the given nested list.
  • The exit of the program.

Below is the implementation:

# function which takes the nested list as argument and
# returnsthe sum of the given nested list.


def sumnestedListRecursion(givenNestedList):
  # Taking a variable that stores the sum of the elements of a nested list
    # and Initialize it with 0.
    totalNestedSum = 0
    # To get the elements inside the sublists, use a for loop and recursion in the function,
    # and store the summed up elements in a variable.
    for eleme in givenNestedList:
        if (type(eleme) == type([])):
            totalNestedSum = totalNestedSum + sumnestedListRecursion(eleme)
        else:
            totalNestedSum = totalNestedSum + eleme
    # return the total sum of all the elements in the given nested list.
    return totalNestedSum


# Give the nested list as static input and store it in a variable.
givenNestedList = [[7, 8, 2], [11, 19, 29, 63, 91], [12, 52, 98], [11, 19, 18],
                   [11, 28, 34, 39, 35, 56, 87, 46, 1, 2], [5], [9, 23], [3, 23, 124]]
# printing the given nested list
print('Printing the given nested list : \n', givenNestedList)
# passing the given nested list as an argument to the recursive function sumnestedListRecursion
# which returns the sum of the given nested list.
print("The sum of all elements of the given nested list is :",
      sumnestedListRecursion(givenNestedList))

Output:

Printing the given nested list : 
 [[7, 8, 2], [11, 19, 29, 63, 91], [12, 52, 98], [11, 19, 18], [11, 28, 34, 39, 35, 56, 87, 46, 1, 2], [5], [9, 23], [3, 23, 124]]
The sum of all elements of the given nested list is : 966

Explanation:

  • A nested list(list of lists) is initialized in a variable.
  • To find the sum of the list’s elements, the list is passed as an argument to a recursive function.
  • A for loop and repeated recursion are used in the function to acquire the elements within the sublists.
  • The sum of the elements is calculated and returned.
  • The sum of the list of lists(nested list) elements is printed.

Related Programs:

Python Program to Find the Total Sum of a Nested List Using Recursion Read More »

Program to Find the Sum of Elements in a List Recursively

Python Program to Find the Sum of Elements in a List Recursively

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Lists in Python:

A list is a Python data type that can be used in a variety of ways. A list is made up of comma-separated values, which are referred to as list items. Within square brackets, a list is declared. It’s worth noting that elements in a list don’t have to be of the same type.

Recursion:

If you’re familiar with Python functions, you’ll know that it’s typical for one function to call another. It is also feasible for a function in Python to call itself! A recursive function calls itself, and the process of using a recursive function is known as recursion.

Although it may appear strange for a function to call itself, many sorts of programming challenges are better stated recursively.

Given a list, the task is to find the sum of the list using recursion in Python.

Examples:

Example1:

Input:

given list = 9, 1, 27, 48, 91, 93, 99, 27, 29, 33, 39, 19, 11, 27, 29, 35, 39, 12, 65, 69, 67

Output:

The sum of the given list
 [9, 1, 27, 48, 91, 93, 99, 27, 29, 33, 39, 19, 11, 27, 29, 35, 39, 12, 65, 69, 67] 
with size  21  = 869

Example2:

Input:

given list =11 13 21 85 34 96 75 73 14 25 37 39 49 47 65 69 63 21 29 123 456 789

Output:

The sum of the given list
[11, 13, 21, 85, 34, 96, 75, 73, 14, 25, 37, 39, 49, 47, 65, 69, 63, 21, 29, 123, 456, 789] 
with size 22 = 2234

Program to Find the Sum of Elements in a List Recursively in Python

Below are the ways to Find the Sum of Elements in a List using the recursive approach in Python:

1)Using Recursion (Static Input)

Approach:

  • Give the input of the list as static input and store it in a variable.
  • Calculate the size of the list using the len() function and store it in a variable.
  • Create a recursive function that accepts an array and its size as parameters.
  • The recursive function will take the list and its size as inputs.
  • Return 0 if the list’s length is zero.
  • Otherwise, along with the recursive function call, return the sum of the last entry of the list (with the size reduced by 1).
  • The final sum is printed when the returned result is saved in a variable.
  • The exit of the Program.

Below is the implementation:

# function which accepts the given list and list size
# as parameters and calculates the sum of the given list using recursion


def sumListRecursion(given_list, sizeOflist):
  # Return 0 if the list's length is zero.(base condition)
    if (sizeOflist == 0):
        return 0
    else:
      # Otherwise, along with the recursive function call,
      # return the sum of the last entry of the list (with the size reduced by 1).

        return given_list[sizeOflist-1] + sumListRecursion(given_list, sizeOflist-1)


# Give the input of the list as static input and store it in a variable.
given_list = [9, 1, 27, 48, 91, 93, 99, 27, 29,
              33, 39, 19, 11, 27, 29, 35, 39, 12, 65, 69, 67]
# Calculate the size of the list using len() function and store it in a variable.
sizeOflist = len(given_list)
# passing the given list and sizeOflist as arguments to the recursive function sumListRecursion.
print('The sum of the given list\n', given_list, '\nwith size ',
      sizeOflist, ' =', sumListRecursion(given_list, sizeOflist))

Output:

The sum of the given list
 [9, 1, 27, 48, 91, 93, 99, 27, 29, 33, 39, 19, 11, 27, 29, 35, 39, 12, 65, 69, 67] 
with size  21  = 869

2)Using Recursion (User Input separated by spaces)

Approach:

  • Scan the given list using map,input(),list() and split() functions.
  • Calculate the size of the list using the len() function and store it in a variable.
  • Create a recursive function that accepts an array and its size as parameters.
  • The recursive function will take the list and its size as inputs.
  • Return 0 if the list’s length is zero.
  • Otherwise, along with the recursive function call, return the sum of the last entry of the list (with the size reduced by 1).
  • The final sum is printed when the returned result is saved in a variable.
  • The exit of the Program.

Below is the implementation:

# function which accepts the given list and list size
# as parameters and calculates the sum of the given list using recursion


def sumListRecursion(given_list, sizeOflist):
  # Return 0 if the list's length is zero.(base condition)
    if (sizeOflist == 0):
        return 0
    else:
      # Otherwise, along with the recursive function call,
      # return the sum of the last entry of the list (with the size reduced by 1).

        return given_list[sizeOflist-1] + sumListRecursion(given_list, sizeOflist-1)


# Scan the given list using map,input(),list() and split() functions.
given_list = list(map(int, input(
    'Enter some random integer elements to the list separated by spaces = ').split()))
# Calculate the size of the list using len() function and store it in a variable.
sizeOflist = len(given_list)
# passing the given list and sizeOflist as arguments to the recursive function sumListRecursion.
print('The sum of the given list\n', given_list, '\nwith size ',
      sizeOflist, ' =', sumListRecursion(given_list, sizeOflist))

Output:

Enter some random integer elements to the list separated by spaces =
 11 13 21 85 34 96 75 73 14 25 37 39 49 47 65 69 63 21 29 123 456 789
The sum of the given list
[11, 13, 21, 85, 34, 96, 75, 73, 14, 25, 37, 39, 49, 47, 65, 69, 63, 21, 29, 123, 456, 789] 
with size 22 = 2234

Explanation:

  • A recursive function is called using the list and its size as parameters.
  • If the function’s size reduces to zero, 0 is returned.
  • Otherwise, the recursive function call (with the size reduced by 1) is returned, along with the sum of the last entry of the list.
  • The returned values are saved in a list, and the sum of the list’s items is printed using the print() function.

Related Programs:

Python Program to Find the Sum of Elements in a List Recursively Read More »

Program to Flatten a Nested List using Recursion

Python Program to Flatten a Nested List using Recursion

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Recursion in Python:

Python also supports function recursion, which means that a specified function can call itself.

Recursion is a mathematical and programming concept that is widely used. It signifies that a function calls itself. This has the advantage of allowing you to loop through data to obtain a result.

The developer must exercise extreme caution when using recursion since it is quite easy to write a function that never terminates or consumes excessive amounts of memory or computing power. However, when performed correctly, recursion may be a tremendously efficient and mathematically elegant way to programming.

Nested List:

A list can include any form of the object, including another list (sublist), which can contain sublists, and so on. This is referred to as a nested list.

Given a nested list, the task is to write a python program that converts the given list to flatted list.

Examples:

I)Integer Nested List

Example1:

Input:

given Nested List = [ [7, 8, 2], [11, 19, 29, 63, 91], [12, 52, 98], [11, 19, 18], 
                                 [11, 28, 34, 39, 35, 56, 87, 46, 1, 2], [5], [9, 23],[3, 23, 124] ]

Output:

Printing the given nested list : 
 [[7, 8, 2], [11, 19, 29, 63, 91], [12, 52, 98], [11, 19, 18], [11, 28, 34, 39, 35, 56, 87, 46, 1, 2], [5], [9, 23], [3, 23, 124]]
Printing the flattened list : 
 [7, 8, 2, 11, 19, 29, 63, 91, 12, 52, 98, 11, 19, 18, 11, 28, 34, 39, 35, 56, 87, 46, 1, 2, 5, 9, 23, 3, 23, 124]

ii)String Nested List

Example2:

Input:

 given Nested List = [ ['hello', 'this'], ['btechgeeks', 'online', 'python'], [ 'programming', 'and'], ['learning', 'platform'],
                                    ['for'], ['coding', 'students']]

Output:

Printing the given nested list : 
 [['hello', 'this'], ['btechgeeks', 'online', 'python'], ['programming', 'and'], ['learning', 'platform'], ['for'], ['coding', 'students']]
Printing the flattened list : 
 ['hello', 'this', 'btechgeeks', 'online', 'python', 'programming', 'and', 'learning', 'platform', 'for', 'coding', 'students']

iii)Random Nested List(Elements can be of any data type)

Example3:

Input:

given nested list = [[928.4, 1], ['btechgeeks', 'online', True], 
                                ['programming', 'and'], ['learning', 'platform'], ['for'], [False, 'students'], [4, 18]]

Output:

Printing the given nested list : 
 [[928.4, 1], ['btechgeeks', 'online', True], ['programming', 'and'], ['learning', 'platform'], ['for'], [False, 'students'], [4, 18]]
Printing the flattened list : 
 [928.4, 1, 'btechgeeks', 'online', True, 'programming', 'and', 'learning', 'platform', 'for', False, 'students', 4, 18]

Program to Flatten a Nested List using Recursion in Python

Below are the ways to Flatten a Nested List using recursion in Python.

Approach:

  • Give the nested list as static input and store it in a variable.
  • To flatten the list, pass it as an argument to a recursive function.
  • If the list is empty, the function returns the list.
  • Otherwise, use the function with the sublists as parameters recursively until the entire list is flattened.
  • Print the list that has been flattened.
  • The exit of the program.

1)Integer Nested List

Below is the implementation:

# function which takes the nested list as argument and
# returns the flattened list using recursion


def flattenListRecursion(given_NestedList):
    # If the list is empty, the function returns the list.
    if given_NestedList == []:
        return given_NestedList
     # Otherwise, use the function with the sublists as parameters
     # recursively until the entire list is flattened.
    if isinstance(given_NestedList[0], list):
        return flattenListRecursion(given_NestedList[0]) + flattenListRecursion(given_NestedList[1:])
    return given_NestedList[:1] + flattenListRecursion(given_NestedList[1:])


# Give the nested list as static input and store it in a variable.
givenNestedList = [[7, 8, 2], [11, 19, 29, 63, 91], [12, 52, 98], [11, 19, 18],
                   [11, 28, 34, 39, 35, 56, 87, 46, 1, 2], [5], [9, 23], [3, 23, 124]]
# printing the given nested list
print('Printing the given nested list : \n', givenNestedList)
# passing the given nested list as an argument to the recursive function flattenListRecursion
# which returns the flattened lsit
print("Printing the flattened list : \n",
      flattenListRecursion(givenNestedList))

Output:

Printing the given nested list : 
 [[7, 8, 2], [11, 19, 29, 63, 91], [12, 52, 98], [11, 19, 18], [11, 28, 34, 39, 35, 56, 87, 46, 1, 2], [5], [9, 23], [3, 23, 124]]
Printing the flattened list : 
 [7, 8, 2, 11, 19, 29, 63, 91, 12, 52, 98, 11, 19, 18, 11, 28, 34, 39, 35, 56, 87, 46, 1, 2, 5, 9, 23, 3, 23, 124]

Explanation:

  • A nested list is initialized in a variable.
  • To flatten the list, the list is given as an argument to a recursive function.
  • If the list is empty, the function returns the list.
  • Otherwise, the function is repeated recursively with the sublists as arguments until the entire list is flattened.
  • The list has been flattened and printed.

2)String Nested List

Below is the implementation:

# function which takes the nested list as argument and
# returns the flattened list using recursion


def flattenListRecursion(given_NestedList):
    # If the list is empty, the function returns the list.
    if given_NestedList == []:
        return given_NestedList
     # Otherwise, use the function with the sublists as parameters
     # recursively until the entire list is flattened.
    if isinstance(given_NestedList[0], list):
        return flattenListRecursion(given_NestedList[0]) + flattenListRecursion(given_NestedList[1:])
    return given_NestedList[:1] + flattenListRecursion(given_NestedList[1:])


# Give the nested list as static input and store it in a variable.
givenNestedList = [['hello', 'this'], ['btechgeeks', 'online', 'python'], [
    'programming', 'and'], ['learning', 'platform'], ['for'], ['coding', 'students']]
# printing the given nested list
print('Printing the given nested list : \n', givenNestedList)
# passing the given nested list as an argument to the recursive function flattenListRecursion
# which returns the flattened lsit
print("Printing the flattened list : \n",
      flattenListRecursion(givenNestedList))

Output:

Printing the given nested list : 
 [['hello', 'this'], ['btechgeeks', 'online', 'python'], ['programming', 'and'], ['learning', 'platform'], ['for'], ['coding', 'students']]
Printing the flattened list : 
 ['hello', 'this', 'btechgeeks', 'online', 'python', 'programming', 'and', 'learning', 'platform', 'for', 'coding', 'students']

3)Random Nested List(Elements can be of any data type)

Below is the implementation:

# function which takes the nested list as argument and
# returns the flattened list using recursion


def flattenListRecursion(given_NestedList):
    # If the list is empty, the function returns the list.
    if given_NestedList == []:
        return given_NestedList
     # Otherwise, use the function with the sublists as parameters
     # recursively until the entire list is flattened.
    if isinstance(given_NestedList[0], list):
        return flattenListRecursion(given_NestedList[0]) + flattenListRecursion(given_NestedList[1:])
    return given_NestedList[:1] + flattenListRecursion(given_NestedList[1:])


# Give the nested list as static input and store it in a variable.
givenNestedList = [[928.4, 1], ['btechgeeks', 'online', True], [
    'programming', 'and'], ['learning', 'platform'], ['for'], [False, 'students'], [4, 18]]
# printing the given nested list
print('Printing the given nested list : \n', givenNestedList)
# passing the given nested list as an argument to the recursive function flattenListRecursion
# which returns the flattened lsit
print("Printing the flattened list : \n",
      flattenListRecursion(givenNestedList))

Output:

Printing the given nested list : 
 [[928.4, 1], ['btechgeeks', 'online', True], ['programming', 'and'], ['learning', 'platform'], ['for'], [False, 'students'], [4, 18]]
Printing the flattened list : 
 [928.4, 1, 'btechgeeks', 'online', True, 'programming', 'and', 'learning', 'platform', 'for', False, 'students', 4, 18]

Related Programs:

Python Program to Flatten a Nested List using Recursion Read More »

Program to Implement Tower of Hanoi Using Recursion

Python Program to Implement Tower of Hanoi Using Recursion

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Recursion in Python:

The Oxford English Dictionary defines recursion as the repeated use of a recursive technique or term.

When a function calls itself repeatedly until it meets a stated stopping condition, this is referred to as recursion. This type of function is known as a recursive function.

The technique of explaining an action in terms of itself is known as recursion.

Use of Recursion:

In general, recursive code is shorter and easier to write than iterative code. When loops are built or interpreted, they are generally transformed into recursive functions. Recursion is most useful for activities that can be broken down into smaller subtasks.

Format of Recursive Function:

A recursive function is made up of two major components:

Base Case: The base case is where all further calls to the same function end, implying that no additional recursive calls are made.
Recursive Case: In the recursive case, the function calls itself till it reaches the base case.
The answer to the primary problem is represented in terms of lesser problems until the smallest problem meets the base case in a recursive function.

Tower of Hanoi:

It is a mathematical puzzle game in which three identical rods and n discs of varying sizes are used. In the first rod, the discs are positioned so that the largest disc is at the bottom and the smallest is at the top. To complete the puzzle, put the discs in the same order in the final rod via the middle rod.

Rules of Towers of Hanoi:

At any given time, only one disc can be transferred.
Each move requires taking the uppermost disc from one of the stacks and placing it on top of another, i.e. a disc can only be moved if it is the uppermost disc on a stack.
A larger disc may not be stacked on top of a smaller disc.

Examples:

Example1:

Input:

given number of disks = 3

Output:

Move disk [1] from rod [ A ] to rod { C }
Move disk [2] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { B }
Move disk [3] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { A }
Move disk [2] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { C }

Example2:

Input:

given number of disks = 4

Output:

Move disk [1] from rod [ A ] to rod { B }
Move disk [2] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }
Move disk [3] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { A }
Move disk [2] from rod [ C ] to rod { B }
Move disk [1] from rod [ A ] to rod { B }
Move disk [4] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }
Move disk [2] from rod [ B ] to rod { A }
Move disk [1] from rod [ C ] to rod { A }
Move disk [3] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { B }
Move disk [2] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }

Program to Implement Tower of Hanoi Using Recursion in Python

1)Using Recursion(Static Input)

Approach:

  • Give the number of discs as static input and store it in a variable.
  • Create a recursive function called tower of Hanoi and pass two arguments: the number of discs n and the names of the rods such as source, aux, and destination.
  • When the number of discs is one, we can define the base case. Simply move the single disc from source to target and return in this scenario.
  • Now, use the target as the auxiliary to shift the remaining n-1 discs from source to auxiliary.
  • The remaining 1 disc then moves from source to target.
  • Use the source as the auxiliary to move the n-1 discs on the auxiliary to the target.

Below is the implementation:

# Create a recursive function called tower of Hanoi and pass two arguments:
# the number of discs n and the names of the rods
# such as source, aux, and destination.


def Towers_Of_Hanoi(numdisks, frm_disc, to_disc, aux_disc):
  # When the number of discs is one, we can define the base case. Simply move the
  # single disc from source to target and return in this scenario.
    if numdisks == 1:
        print("Move disk [1] from rod [",
              frm_disc, "] to rod {", to_disc, '}')
        return
    # Now, use the target as the auxiliary to
    # shift the remaining n-1 discs from source to auxiliary.
    Towers_Of_Hanoi(numdisks-1, frm_disc, aux_disc, to_disc)
    # The remaining 1 disc then moves from source to target.

    # Use the source as the auxiliary to move the n-1 discs on the auxiliary to the target.
    print("Move disk ["+str(numdisks) + "] from rod [",
          str(frm_disc)+" ] to rod {", to_disc, '}')
    Towers_Of_Hanoi(numdisks-1, aux_disc, to_disc, frm_disc)


# Give the number of discs as static input and store it in a variable.
numdisks = 4
# passing the given number of disks as argument to the towers of hanoi recursive function .
Towers_Of_Hanoi(numdisks, 'A', 'C', 'B')

Output:

Move disk [1] from rod [ A ] to rod { B }
Move disk [2] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }
Move disk [3] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { A }
Move disk [2] from rod [ C ] to rod { B }
Move disk [1] from rod [ A ] to rod { B }
Move disk [4] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }
Move disk [2] from rod [ B ] to rod { A }
Move disk [1] from rod [ C ] to rod { A }
Move disk [3] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { B }
Move disk [2] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { C }

2)Using Recursion(User Input)

Approach:

  • Give the number of discs as user input using the int(input()) function which converts the string to an integer.
  • Store it in a variable.
  • Create a recursive function called tower of Hanoi and pass two arguments: the number of discs n and the names of the rods such as source, aux, and destination.
  • When the number of discs is one, we can define the base case. Simply move the single disc from source to target and return in this scenario.
  • Now, use the target as the auxiliary to shift the remaining n-1 discs from source to auxiliary.
  • The remaining 1 disc then moves from source to target.
  • Use the source as the auxiliary to move the n-1 discs on the auxiliary to the target.

Below is the implementation:

# Create a recursive function called tower of Hanoi and pass two arguments:
# the number of discs n and the names of the rods
# such as source, aux, and destination.


def Towers_Of_Hanoi(numdisks, frm_disc, to_disc, aux_disc):
  # When the number of discs is one, we can define the base case. Simply move the
  # single disc from source to target and return in this scenario.
    if numdisks == 1:
        print("Move disk [1] from rod [",
              frm_disc, "] to rod {", to_disc, '}')
        return
    # Now, use the target as the auxiliary to
    # shift the remaining n-1 discs from source to auxiliary.
    Towers_Of_Hanoi(numdisks-1, frm_disc, aux_disc, to_disc)
    # The remaining 1 disc then moves from source to target.

    # Use the source as the auxiliary to move the n-1 discs on the auxiliary to the target.
    print("Move disk ["+str(numdisks) + "] from rod [",
          str(frm_disc)+" ] to rod {", to_disc, '}')
    Towers_Of_Hanoi(numdisks-1, aux_disc, to_disc, frm_disc)


# Give the number of discs as user input using
# the int(input()) function which converts the string to an integer.
# Store it in a variable.
numdisks = int(input('Enter some random number of disks = '))
# passing the given number of disks as argument to the towers of hanoi recursive function .
Towers_Of_Hanoi(numdisks, 'A', 'C', 'B')

Output:

Enter some random number of disks = 5
Move disk [1] from rod [ A ] to rod { C }
Move disk [2] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { B }
Move disk [3] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { A }
Move disk [2] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { C }
Move disk [4] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { B }
Move disk [2] from rod [ C ] to rod { A }
Move disk [1] from rod [ B ] to rod { A }
Move disk [3] from rod [ C ] to rod { B }
Move disk [1] from rod [ A ] to rod { C }
Move disk [2] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { B }
Move disk [5] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { A }
Move disk [2] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { C }
Move disk [3] from rod [ B ] to rod { A }
Move disk [1] from rod [ C ] to rod { B }
Move disk [2] from rod [ C ] to rod { A }
Move disk [1] from rod [ B ] to rod { A }
Move disk [4] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { C }
Move disk [2] from rod [ A ] to rod { B }
Move disk [1] from rod [ C ] to rod { B }
Move disk [3] from rod [ A ] to rod { C }
Move disk [1] from rod [ B ] to rod { A }
Move disk [2] from rod [ B ] to rod { C }
Move disk [1] from rod [ A ] to rod { C }

It prints all the valid moves of the disks.

Related Programs:

Python Program to Implement Tower of Hanoi Using Recursion Read More »

Python Program to Find Number of Digits in Nth Fibonacci Number

Python Program to Find Number of Digits in Nth Fibonacci Number

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Given a number N the task is to calculate the number of digits in the Nth Fibonacci Number.

Fibonacci Numbers:

Starting with 0 and 1, the next two numbers are simply the sum of the previous two numbers. The third number in this sequence, for example, is 0+1=1, hence the third number is 1. Similarly, the fourth number in this series will be 1+1=2, resulting in the fourth number being 2.
The Fibonacci Number Series is as follows: 0 1 1 2 3 5 8 13 21 and so on.

Examples:

Example1:

Input:

Given N=14

Output:

The Number of digits present in 14 th Fibonacci number is [ 3 ]

Example2:

Input:

Given N=23

Output:

The 23 th Fibonacci number is [ 17711 ]
The Number of digits present in 23 th Fibonacci number is [ 5 ]

Python Program to Find Number of Digits in Nth Fibonacci Number

Below are the ways to find the number of digits in the Nth Fibonacci Number.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number N as static input and store it in a variable.
  • Take a variable temp1 and initialize its value to 0.
  • Take another variable temp2 and initialize its value to 1.
  • Loop till N-2 using For loop.
  • Increment the value of temp1 by temp1 i.e temp1=temp1+temp2.
  • Swap the values of temp1,temp2 using the ‘,’ operator.
  • Check if the value of the given number N is 1 or not using the If statement.
  • If it is true then print the value of temp1 which is the value of the nth Fibonacci number.
  • Else print the value of temp2 which is the value of the nth Fibonacci number.
  • Calculate the number of digits by converting it to string.
  • Calculate the length of string which is the number of digits in the nth Fibonacci Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number N as static input and store it in a variable.
numbr = 14
# Take a variable temp1 and initialize its value to 0.
temp1 = 0
# Take another variable temp2 and initialize its value to 1.
temp2 = 1
# Loop till N-2 using For loop.
for z in range(numbr-2):
    # Increment the value of temp1 by temp1 i.e temp1=temp1+temp2.
    temp1 = temp1+temp2
    # Swap the values of temp1,temp2 using the ',' operator.
    temp1, temp2 = temp2, temp1
# Check if the value of the given number N is 1 or not using the If statement.
if(numbr == 1):
  # If it is true then print the value of temp1 which is the value of the nth Fibonacci number
    print('The', numbr, 'th Fibonacci number is [', temp1, ']')
# Else print the value of temp2 which is the value of the nth Fibonacci number.
else:
    print('The', numbr, 'th Fibonacci number is [', temp2, ']')
# Calculate the number of digits by converting it to string.
stringnumbr = str(temp2)
# Calculate the length of string which is the number of digits in the nth Fibonacci Number.
nLen = len(stringnumbr)
print('The Number of digits present in', numbr,
      'th Fibonacci number is [', nLen, ']')

Output:

The 14 th Fibonacci number is [ 233 ]
The Number of digits present in 14 th Fibonacci number is [ 3 ]

Method #2: Using For Loop (User Input)

Approach:

  • Give the number N as user input using int(input()) and store it in a variable.
  • Take a variable temp1 and initialize its value to 0.
  • Take another variable temp2 and initialize its value to 1.
  • Loop till N-2 using For loop.
  • Increment the value of temp1 by temp1 i.e temp1=temp1+temp2.
  • Swap the values of temp1,temp2 using the ‘,’ operator.
  • Check if the value of the given number N is 1 or not using the If statement.
  • If it is true then print the value of temp1 which is the value of the nth Fibonacci number.
  • Else print the value of temp2 which is the value of the nth Fibonacci number.
  • Calculate the number of digits by converting it to string.
  • Calculate the length of string which is the number of digits in the nth Fibonacci Number.
  • The Exit of the Program.

Below is the implementation:

# Give the number N as user input using int(input()) and store it in a variable.
numbr = int(input('Enter some random nth number = '))
# Take a variable temp1 and initialize its value to 0.
temp1 = 0
# Take another variable temp2 and initialize its value to 1.
temp2 = 1
# Loop till N-2 using For loop.
for z in range(numbr-2):
    # Increment the value of temp1 by temp1 i.e temp1=temp1+temp2.
    temp1 = temp1+temp2
    # Swap the values of temp1,temp2 using the ',' operator.
    temp1, temp2 = temp2, temp1
# Check if the value of the given number N is 1 or not using the If statement.
if(numbr == 1):
  # If it is true then print the value of temp1 which is the value of the nth Fibonacci number
    print('The', numbr, 'th Fibonacci number is [', temp1, ']')
# Else print the value of temp2 which is the value of the nth Fibonacci number.
else:
    print('The', numbr, 'th Fibonacci number is [', temp2, ']')
# Calculate the number of digits by converting it to string.
stringnumbr = str(temp2)
# Calculate the length of string which is the number of digits in the nth Fibonacci Number.
nLen = len(stringnumbr)
print('The Number of digits present in', numbr,
      'th Fibonacci number is [', nLen, ']')

Output:

Enter some random nth number = 23
The 23 th Fibonacci number is [ 17711 ]
The Number of digits present in 23 th Fibonacci number is [ 5 ]

Related Programs:

Python Program to Find Number of Digits in Nth Fibonacci Number Read More »