Python

Program to Check Even or Odd Using Bitwise Operator

Python Program to Check Even or Odd Using Bitwise Operator

In the previous article, we have discussed Python Program to Set nth Bit of a Number

Given a Number and the task is to check if the given number is even or odd using the bitwise operator.

Bitwise & Operator:

If both bits are 1, sets each bit to 1.

Examples:

Example1:

Input:

Given Number = 251

Output:

The Number given is an Odd Number

Example2:

Input:

Given Number = 54

Output:

The Number given is an Even Number

Program to Check Even or Odd Using Bitwise Operator in Python:

Below are the ways to check if the given number is even or odd using the bitwise operator in python:

Method #1: Using Bitwise &(and) Operator (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Apply bitwise & operation for the given number and 1 and store it in another variable say evn_or_od.
  • Pass the above result to the if conditional statement.
  • If the statement is true, then print “The Number given is an Odd Number”.
  • Else print “The Number given is an Even Number”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 251
# Apply bitwise & operation for the given number and 1 and store it in another variable
# say evn_or_od.
evn_or_od = gvn_numb & 1
# Pass the above result to the if conditional statement.
if (evn_or_od):
    # If the statement is true, then print "The Number given is an Odd Number".
    print("The Number given is an Odd Number")
else:
    # Else print "The Number given is an Even Number".
    print("The Number given is an Even Number")

Output:

The Number given is an Odd Number

Method #2: Using Bitwise &(and) Operator (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Apply bitwise & operation for the given number and 1 and store it in another variable say evn_or_od.
  • Pass the above result to the if conditional statement.
  • If the statement is true, then print “The Number given is an Odd Number”.
  • Else print “The Number given is an Even Number”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and 
# store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Apply bitwise & operation for the given number and 1 and store it in another variable
# say evn_or_od.
evn_or_od = gvn_numb & 1
# Pass the above result to the if conditional statement.
if (evn_or_od):
    # If the statement is true, then print "The Number given is an Odd Number".
    print("The Number given is an Odd Number")
else:
    # Else print "The Number given is an Even Number".
    print("The Number given is an Even Number")

Output:

Enter some random number = 32
The Number given is an Even Number

Grab the opportunity and utilize the Python Program Code Examples over here to prepare basic and advanced topics too with ease and clear all your doubts.

Python Program to Check Even or Odd Using Bitwise Operator Read More »

Program to Get nth Bit of a Number

Python Program to Get nth Bit of a Number

In the previous article, we have discussed Program to Find All Non Repeated Characters in a String

Given a number and the bit position, the task is to get the bit that is present at that position (in the binary representation of a number).

Bitwise & Operator:

If both bits are 1, sets each bit to 1.

Examples:

Example1:

Input:

Given Number = 2
Bit position(in range 0-31)= 0

Output:

The bit present at the given position{ 0 } for a given number is 0

Example2:

Input:

Given Number = 14
Bit position(in range 0-31)= 3

Output:

The bit present at the given position{ 3 } for a given number is 1

Program to Get nth Bit of a Number in Python

Below are the ways to get the bit that is present at that position (in the binary representation of a number) in python:

Method #1: Using Bitwise &(and) Operator (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Give the bit position that you need to get the bit value at that position as static input and store it in another variable.
  • Apply the left shift operator to 1 and the above-given bit position and store it in another variable.
  • Apply bitwise & operation for the given number and the above result and store it in another variable say bit_val.
  • Check if the above result bit_val is greater than 0 using the if conditional statement.
  • If the statement is true, then print “The bit present at the given position for a given number is 1”.
  • Else print “The bit present at the given position for a given number is 0”.
  • The Exit of the Program.

Note: ‘0’ indexing .Give the bit position in range(0-31).

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 2
# Give the bit position that you need to get the bit value at that position as static input
# and store it in another variable.
bitpositin = 0
# Apply the left shift operator to 1 and the above-given bit position and
# store it in another variable.
numbr_bit = (1 << bitpositin)
# Apply bitwise & operation for the given number and the above result and
# store it in another variable say bit_val.
bit_val = gvn_numb & numbr_bit
# Check if the above result bit_val is greater than 0 using the if conditional statement.
if (bit_val > 0):
    # If the statement is true, then print "The bit present at the given position is 1".
    print(
        "The bit present at the given position{", bitpositin, "} for a given number is 1")
else:
    # Else print "The bit present at the given position is 0".
    print(
        "The bit present at the given position{", bitpositin, "} for a given number is 0")

Output:

The bit present at the given position{ 0 } for a given number is 0

Method #2: Using Bitwise &(and) Operator (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the bit position that you need to get the bit value at that position as user input using the int(input()) function and store it in another variable.
  • Apply the left shift operator to 1 and the above-given bit position and store it in another variable.
  • Apply bitwise & operation for the given number and the above result and store it in another variable say bit_val.
  • Check if the above result bit_val is greater than 0 using the if conditional statement.
  • If the statement is true, then print “The bit present at the given position for a given number is 1”.
  • Else print “The bit present at the given position for a given number is 0”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and 
# store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Give the bit position that you need to get the bit value at that position as user input
# using the int(input()) function and store it in another variable.
bitpositin = int(input("Enter some random number = "))
# Apply the left shift operator to 1 and the above-given bit position and
# store it in another variable.
numbr_bit = (1 << bitpositin)
# Apply bitwise & operation for the given number and the above result and
# store it in another variable say bit_val.
bit_val = gvn_numb & numbr_bit
# Check if the above result bit_val is greater than 0 using the if conditional statement.
if (bit_val > 0):
    # If the statement is true, then print "The bit present at the given position is 1".
    print(
        "The bit present at the given position{", bitpositin, "} for a given number is 1")
else:
    # Else print "The bit present at the given position is 0".
    print(
        "The bit present at the given position{", bitpositin, "} for a given number is 0")

Output:

Enter some random number = 14
Enter some random number = 3
The bit present at the given position{ 3 } for a given number is 1

If you wanna write simple python programs as a part of your coding practice refer to numerous Simple Python Program Examples existing and learn the approach used.

Python Program to Get nth Bit of a Number Read More »

Program to Find All Non Repeated Characters in a String

Python Program to Find All Non Repeated Characters in a String

In the previous article, we have discussed Program to Find Lexicographic Rank of a Given String

Given a string and the task is to find all the Non repeated characters in a given String.

Counter function in Python:

The counter is a set and dict subset. Counter() takes an iterable entity as an argument and stores the elements as keys and the frequency of the elements as a value. So, in collections, if we transfer a string. When you call Counter(), you’ll get a Counter class object with characters as keys and their frequency in a string as values.

Counter() returns a Counter type object (a subclass of dict) with all characters in the string as keys and their occurrence count as values. We’ll use the [] operator to get the occurrence count of the characters from it.

Examples:

Example1:

Input:

Given String = "hello this is btechgeeks"

Output:

In a Given String,{ hello this is btechgeeks } all Non-repeating Characters are:
o b c g k

Example2:

Input:

Given String = "good morning btechgeeks"

Output:

In a Given String,{ good morning btechgeeks } all Non-repeating Characters are:
d m r i b t c h k s

Program to Find All Non-Repeated Characters in a String in Python

Below are the ways to find all the Non repeated characters in a given String:

Method #1: Using Counter() function (Hashing, Static Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string as static input and store it in a variable.
  • Calculate the frequency of all the given string elements using the Counter() function which returns the element and its frequency as a key-value pair and stores this dictionary in another variable (say strngfreqelements).
  • Traverse in this frequency dictionary using the for loop.
  • Inside the loop, check if the Key has the frequency 1 and key not equal to space using the if conditional statement
  • If the statement is true, then print the value of the key.
  • The Exit of the program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the string as static input and store it in a variable.
gven_str = "hello this is btechgeeks"
# Calculate the frequency of all the given string elements using the Counter() function
# which returns the element and its frequency as a key-value pair and stores this
# dictionary in another variable (say strngfreqelements).
strngfreqelements = Counter(gven_str)
print("In a Given String,{", gven_str, "} all Non-repeating Characters are:")
# Traverse in this frequency dictionary using the for loop.
for key in strngfreqelements:
    # Inside the loop, check if the Key has the frequency 1 and key not equal to space
    # using the if conditional statement
    if(strngfreqelements[key] == 1 and key != " "):
     # If the statement is true, then print the value of the key.
        print(key, end=" ")

Output:

In a Given String,{ hello this is btechgeeks } all Non-repeating Characters are:
o b c g k

Method #2: Using Counter() function (Hashing, User Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string as user input using the input() function and store it in a variable.
  • Calculate the frequency of all the given string elements using the Counter() function which returns the element and its frequency as a key-value pair and stores this dictionary in another variable (say strngfreqelements).
  • Traverse in this frequency dictionary using the for loop.
  • Inside the loop, check if the Key has the frequency 1 and key not equal to space using the if conditional statement
  • If the statement is true, then print the value of the key.
  • The Exit of the program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the string as user input using the input() function and 
# store it in a variable.
gven_str = input("Enter some random String = ")
# Calculate the frequency of all the given string elements using the Counter() function
# which returns the element and its frequency as a key-value pair and stores this
# dictionary in another variable (say strngfreqelements).
strngfreqelements = Counter(gven_str)
print("In a Given String,{", gven_str, "} all Non-repeating Characters are:")
# Traverse in this frequency dictionary using the for loop.
for key in strngfreqelements:
    # Inside the loop, check if the Key has the frequency 1 and key not equal to space
    # using the if conditional statement
    if(strngfreqelements[key] == 1 and key != " "):
     # If the statement is true, then print the value of the key.
        print(key, end=" ")

Output:

Enter some random String = good morning btechgeeks
In a Given String,{ good morning btechgeeks } all Non-repeating Characters are:
d m r i b t c h k s

Find a comprehensive collection of Examples of Python Programs ranging from simple ones to complex ones to guide you throughout your coding journey.

Python Program to Find All Non Repeated Characters in a String Read More »

Program to Find Lexicographic Rank of a Given String

Python Program to Find Lexicographic Rank of a Given String

In the previous article, we have discussed Python Program to Check if a String Contains at least One Number

Given a string and the task is to find the Lexicographic Rank of a given string in python.

Examples:

Example1:

Input:

Given String = "btechgeeks"

Output:

The given String's { btechgeeks } Lexicographic Rank =  328009

Example2:

Input:

Given String = "hello"

Output:

The given String's { hello } Lexicographic Rank =  25

Program to Find Lexicographic Rank of a Given String in Python

Below are the ways to find the Lexicographic Rank of a given string in python.

Method #1: Using For Loop (Static Input)

Approach:

  • Import math module using the import keyword.
  • Give the string as static input and store it in a variable.
  • Take a variable to say lexicogrpc_rank and initialize its value to 1.
  • Calculate the length of the given string using the len() function and decrease it by 1.
  • Store it in another variable say str_lengt.
  • Loop from 0 to the above length using the for loop.
  • Inside the loop, take a variable to say cnt and initialize its value to 0.
  • Loop from the itr+1 to the above str_lengt (where itr is the iterator value of the parent for loop) using the for loop.
  • Inside the loop, check if the character present at the iterator value of the parent for loop is greater than the character present at the iterator value of the inner for loop using the if conditional statement.
  • If the statement is true, then increment the value of the above-initialized cnt by 1.
  • Calculate the factorial of (str_lengt – itr) using the math.factorial() function and store it in another variable. (where itr is the iterator value of the parent for loop)
  • Multiply the above result with cnt and add the result to the lexicogrpc_rank.
  • Store it in the same variable lexicogrpc_rank.
  • Print the lexicogrpc_rank to get the Lexicographic Rank of a given string.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the string as static input and store it in a variable.
gven_str = "btechgeeks"
# Take a variable to say lexicogrpc_rank and initialize its value to 1.
lexicogrpc_rank = 1
# Calculate the length of the given string using the len() function and decrease it by 1.
# Store it in another variable say str_lengt.
str_lengt = len(gven_str)-1
# Loop from 0 to the above length using the for loop.
for itr in range(0, str_lengt):
    # Inside the loop, take a variable to say cnt and initialize its value to 0.
    cnt = 0
    # Loop from the itr+1 to the above str_lengt (where itr is the iterator value of the parent
    # for loop) using the for loop.
    for k in range(itr+1, str_lengt+1):
      # Inside the loop, check if the character present at the iterator value of the parent for
      # loop is greater than the character present at the iterator value of the inner for
      # loop using the if conditional statement.
        if gven_str[itr] > gven_str[k]:
         # If the statement is true, then increment the value of the above-initialized cnt by 1.

            cnt += 1
    # Calculate the factorial of (str_lengt - itr) using the math.factorial() function and
    # store it in another variable. (where itr is the iterator value of the parent for loop)
    f = math.factorial(str_lengt-itr)
    # Multiply the above result with cnt and add the result to the lexicogrpc_rank.
    # Store it in the same variable lexicogrpc_rank.
    lexicogrpc_rank += cnt*f
# Print the lexicogrpc_rank to get the Lexicographic Rank of a given string.
print("The given String's {", gven_str,
      "} Lexicographic Rank = ", lexicogrpc_rank)

Output:

The given String's { btechgeeks } Lexicographic Rank =  328009

Method #2: Using For loop (User Input)

Approach:

  • Import math module using the import keyword.
  • Give the string as user input using the input() function and store it in a variable.
  • Take a variable to say lexicogrpc_rank and initialize its value to 1.
  • Calculate the length of the given string using the len() function and decrease it by 1.
  • Store it in another variable say str_lengt.
  • Loop from 0 to the above length using the for loop.
  • Inside the loop, take a variable to say cnt and initialize its value to 0.
  • Loop from the itr+1 to the above str_lengt (where itr is the iterator value of the parent for loop) using the for loop.
  • Inside the loop, check if the character present at the iterator value of the parent for loop is greater than the character present at the iterator value of the inner for loop using the if conditional statement.
  • If the statement is true, then increment the value of the above-initialized cnt by 1.
  • Calculate the factorial of (str_lengt – itr) using the math.factorial() function and store it in another variable. (where itr is the iterator value of the parent for loop)
  • Multiply the above result with cnt and add the result to the lexicogrpc_rank.
  • Store it in the same variable lexicogrpc_rank.
  • Print the lexicogrpc_rank to get the Lexicographic Rank of a given string.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the string as user input using the input() function and 
# store it in a variable.
gven_str = input("Enter some random String = ")
# Take a variable to say lexicogrpc_rank and initialize its value to 1.
lexicogrpc_rank = 1
# Calculate the length of the given string using the len() function and decrease it by 1.
# Store it in another variable say str_lengt.
str_lengt = len(gven_str)-1
# Loop from 0 to the above length using the for loop.
for itr in range(0, str_lengt):
    # Inside the loop, take a variable to say cnt and initialize its value to 0.
    cnt = 0
    # Loop from the itr+1 to the above str_lengt (where itr is the iterator value of the parent
    # for loop) using the for loop.
    for k in range(itr+1, str_lengt+1):
      # Inside the loop, check if the character present at the iterator value of the parent for
      # loop is greater than the character present at the iterator value of the inner for
      # loop using the if conditional statement.
        if gven_str[itr] > gven_str[k]:
         # If the statement is true, then increment the value of the above-initialized cnt by 1.

            cnt += 1
    # Calculate the factorial of (str_lengt - itr) using the math.factorial() function and
    # store it in another variable. (where itr is the iterator value of the parent for loop)
    f = math.factorial(str_lengt-itr)
    # Multiply the above result with cnt and add the result to the lexicogrpc_rank.
    # Store it in the same variable lexicogrpc_rank.
    lexicogrpc_rank += cnt*f
# Print the lexicogrpc_rank to get the Lexicographic Rank of a given string.
print("The given String's {", gven_str,
      "} Lexicographic Rank = ", lexicogrpc_rank)

Output:

Enter some random String = hello
The given String's { hello } Lexicographic Rank = 25

Find the best practical and ready-to-use Python Programming Examples that you can simply run on a variety of platforms and never stop learning.

Python Program to Find Lexicographic Rank of a Given String Read More »

Program to Check if a String Contains at least One Number

Python Program to Check if a String Contains at least One Number

In the previous article, we have discussed Python Program to Find the Shortest Word in a String

Given a string and the task is to check whether the given string contains at least one number in it.

Examples:

Example1:

Input:

Given String = "Hello 123 this is BTechGeeks online Platform "

Output:

Yes, the above given string has at least one digit in it

Example2:

Input:

Given String = "good morning btechgeeks"

Output:

No, the above-given string doesn't have at least one digit in it

Program to Check if a String Contains at least One Number in Python

Below are the ways to check whether the given string contains at least one number in python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a variable say k and initialize its value to 0.
  • Calculate the length of the given string using the len() function store it in another variable.
  • Loop from 0 to the length of the given string using the for loop.
  • Check if the character present at the iterator value of the given string string is greater than or equal to 0 and less than or equal to 9 using the if conditional statement.
  • If the statement is true, then increment the value of the above-initialized k by 1.
  • Exit the loop.
  • Check if the value of k is greater than or equal to 1 using the if conditional statement.
  • If the statement is true, then print “Yes, the above-given string has at least one digit in it”.
  • Else print “No, the above-given string doesn’t have at least one digit in it”.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "Hello 123 this is BTechGeeks online Platform "
# Take a variable say k and initialize its value to 0.
k = 0
# Calculate the length of the given string using the len() function.
# store it in another variable.
str_lengt = len(gvn_str)
# Loop from 0 to the length of the given string using the for loop.
for itr in range(0, str_lengt):
  # Check if the character present at the iterator value of the given string string is
  # greater than or equal to 0 and less than or equal to 9 using the if
  # conditional statement.
    if gvn_str[itr] >= '0' and gvn_str[itr] <= '9':
        # If the statement is true, then increment the value of the above-initialized k by 1.
        # Exit the loop.
        k += 1
# Check if the value of k is greater than or equal to 1 using the if conditional statement.
if k >= 1:
    # If the statement is true, then print "Yes, the above-given string has at least one
    # digit in it".
    print("Yes, the above given string has at least one digit in it")
else:
    # Else print "No, the above-given string doesn't have at least one digit in it".
    print("No, the above-given string doesn't have at least one digit in it")

Output:

Yes, the above given string has at least one digit in it

Method #2: Using For loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take a variable say k and initialize its value to 0.
  • Calculate the length of the given string using the len() function store it in another variable.
  • Loop from 0 to the length of the given string using the for loop.
  • Check if the character present at the iterator value of the given string string is greater than or equal to 0 and less than or equal to 9 using the if conditional statement.
  • If the statement is true, then increment the value of the above-initialized k by 1.
  • Exit the loop.
  • Check if the value of k is greater than or equal to 1 using the if conditional statement.
  • If the statement is true, then print “Yes, the above-given string has at least one digit in it”.
  • Else print “No, the above-given string doesn’t have at least one digit in it”.
  • The Exit of the program.

Below is the implementation:

# Give the string as user input using the input() function and
# store it in a variable.
gvn_str = input("Enter some random String = ")
# Take a variable say k and initialize its value to 0.
k = 0
# Calculate the length of the given string using the len() function.
# store it in another variable.
str_lengt = len(gvn_str)
# Loop from 0 to the length of the given string using the for loop.
for itr in range(0, str_lengt):
  # Check if the character present at the iterator value of the given string string is
  # greater than or equal to 0 and less than or equal to 9 using the if
  # conditional statement.
    if gvn_str[itr] >= '0' and gvn_str[itr] <= '9':
        # If the statement is true, then increment the value of the above-initialized k by 1.
        # Exit the loop.
        k += 1
# Check if the value of k is greater than or equal to 1 using the if conditional statement.
if k >= 1:
    # If the statement is true, then print "Yes, the above-given string has at least one
    # digit in it".
    print("Yes, the above given string has at least one digit in it")
else:
    # Else print "No, the above-given string doesn't have at least one digit in it".
    print("No, the above-given string doesn't have at least one digit in it")

Output:

Enter some random String = good morning btechgeeks
No, the above-given string doesn't have at least one digit in it

Access the big list of Python Programming Code Examples with actual logical code asked in Programming and Coding Interviews for Python and stand out from the crowd.

Python Program to Check if a String Contains at least One Number Read More »

Program to Find the Shortest Word in a String

Python Program to Find the Shortest Word in a String

In the previous article, we have discussed Program to Print First 50 Natural Numbers Using Recursion

Given a string and the task is to find the shortest word in a given string.

Examples:

Example1:

Input:

Given String = "Hello this is BTechGeeks online Platform"

Output:

Printing the shortest length word :
is

Example2:

Input:

Given String = "good morning btechgeeks"

Output:

Printing the shortest length word :
good

Program to Find the Shortest Word in a String in Python

Below are the ways to find the shortest word in a given string:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Convert the given string into a list of words using the list() and split() functions and store it in a variable.
  • Assume that the first element is the one with the shortest word.
  • The lengths of the words in the list are then compared with the first element using a for loop and an if statement.
  • In a temporary variable, save the name of the term with the shortest length.
  • Print the word that has the shortest length.
  • The Exit of program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str="Hello this is BTechGeeks online Platform "
# Convert the given string into a list of words using the list(),split() functions and
#store it in a variable.
listWords = list(gvn_str.split())
# taking the first element length as min length word
minLength = len(listWords[0])
# Initializing a temp variable which stores the first word
word = listWords[0]
# Traversing the words list
for i in listWords:
    if(len(i) < minLength):
        minLength = len(i)
        word = i
print("Printing the shortest length word :")
print(word)

Output:

Printing the shortest length word :
is

Method #2: Using For loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Convert the given string into a list of words using the list() and split() functions and store it in a variable.
  • Assume that the first element is the one with the shortest word.
  • The lengths of the words in the list are then compared with the first element using a for loop and an if statement.
  • In a temporary variable, save the name of the term with the shortest length.
  • Print the word that has the shortest length.
  • The Exit of program.

Below is the implementation:

# Give the string as user input using the input() function 
# and store it in a variable.
gvn_str= input("Enter some random String = ")
# Convert the given string into a list of words using the list(),split() functions and
#store it in a variable.
listWords = list(gvn_str.split())
# taking the first element length as min length word
minLength = len(listWords[0])
# Initializing a temp variable which stores the first word
word = listWords[0]
# Traversing the words list
for i in listWords:
    if(len(i) < minLength):
        minLength = len(i)
        word = i
print("Printing the shortest length word :")
print(word)

Output:

Enter some random String = good morning btechgeeks
Printing the shortest length word :
good

The best way to learn Python for Beginners is to practice as much as they can taking help of the Sample Python Programs For Beginners. Using them you can develop code on your own and master coding skills.

Python Program to Find the Shortest Word in a String Read More »

Program to Print First 50 Natural Numbers Using Recursion

Python Program to Print First 50 Natural Numbers Using Recursion

In the previous article, we have discussed Python Program to find the Normal and Trace of a Matrix

The task is to print the first 50 natural numbers using recursion.

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.

Natural Numbers:

Natural numbers are a subset of the number system that includes all positive integers from one to infinity. Natural numbers, which do not include zero or negative numbers, are also known as counting numbers. They are a subset of real numbers that include only positive integers and exclude zero, fractions, decimals, and negative numbers.

Program to Print First 50 Natural Numbers Using Recursion in Python

Below are the ways to print the first 50 natural numbers using recursion.

Method : Using Recursion

Approach:

  • Take a variable say gvn_numb and initialize its value to 1 and store it in a variable.
  • Pass the given number as an argument to the NaturlNumbr function.
  • Create a recursive function to say NaturlNumbr which takes the given number as an argument and returns the first 50 natural numbers.
  • Check if the given number is less than or equal to 50 using the if conditional statement.
  • If the statement is true, print the given number separated by spaces.
  • Pass the given number +1 as an argument to the NaturlNumbr function.{Recursive Logic}
  • Print the first 50 natural numbers using recursion.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say NaturlNumbr which takes the given number as an
# argument and returns the first 50 natural numbers.


def NaturlNumbr(gvn_numb):
    # Check if the given number is less than or equal to 50 using the if conditional
    # statement.
    if(gvn_numb <= 50):
      # If the statement is true, print the given number separated by spaces.
        print(gvn_numb, end=" ")
      # Pass the given number +1 as an argument to the NaturlNumbr function.{Recursive Logic}
        NaturlNumbr(gvn_numb + 1)


# Take a variable say gvn_numb and initialize its value to 1 and store it in a variable.
# Print the first 50 natural numbers using recursion.
gvn_numb = 1
# Pass the given number as an argument to the NaturlNumbr function.
print("The first 50 natural numbers are as follows:")
NaturlNumbr(gvn_numb)

Output:

The first 50 natural numbers are as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

Enhance your coding skills with our list of Python Basic Programs provided and become a pro in the general-purpose programming language Python in no time.

Python Program to Print First 50 Natural Numbers Using Recursion Read More »

Program to find the Normal and Trace of a Matrix

Python Program to find the Normal and Trace of a Matrix

In the previous article, we have discussed Python Program to Print Odd Numbers in Given Range Using Recursion

Given a matrix and the task is to find the normal and trace of the given Matrix in Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Normal of a matrix:

The sum of squares is normal for all the matrix entries.

Trace of a matrix:

Trace is the sum of the Matrix’s diagonal parts.

Examples:

Example1:

Input:

Given Matix :
2 6 4 
8 5 3 
1 6 8

Output:

The trace value of the given matrix is : 15
The normal value of the given matrix is : 6.557438524302

Example2:

Input:

Given Matix : 
1 2 3 4
7 5 8 6
9 4 2 5
1 1 1 1

Output:

The trace value of the given matrix is : 9
The normal value of the given matrix is : 7.745966692414834

Program to find the Normal and Trace of a Matrix in Python

Below are the ways to find the normal and trace of the given Matrix in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Import the math module using the import keyword.
  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Take a variable say mtrxtrace which stores the trace of the given matrix and initialize its value to 0.
  • Take a variable say mtrxsum which stores the sum of all elements of the matrix and initialize its value to 0.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the parent loop iterator value is equal to the inner loop iterator value using the if conditional statement(This is whether the element is diagonal element or not)
  • If it is true then add this value to mtrxtrace.
  • After the if conditional statement, Add the gvnmatrix[n][m] to the above-initialized mtrxsum and store it in the same variable mtrxsum.
  • After the end of two loops calculate the square root of the mtrxsum value using the sqrt() function and store this result in mtrxnormal variable.
  • Print the value of mtrxtrace which gives the value of the trace of the given matrix.
  • Print the value of mtrxnormal which gives the value of the normal of the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the matrix as static input and store it in a variable.
mtrx = [[2, 6, 4], [8, 5, 3], [1, 6, 8]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
# Take a variable say mtrxtrace which stores the trace of the given matrix
# and initialize its value to 0.
mtrxtrace = 0
# Take a variable say mtrxsum which stores the sum of all elements of the matrix
# and initialize its value to 0.
mtrxsum = 0
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the parent loop iterator value is equal to the inner loop iterator value
        # using the if conditional statement
        # (This is whether the element is diagonal element or not)
        if(n == m):
            # If it is true then add this value to mtrxtrace.
            mtrxtrace = mtrxtrace+mtrx[n][m]

        # After the if conditional statement,
        # Add the gvnmatrix[n][m] to the above-initialized mtrxsum
        # and store it in the same variable mtrxsum.
        mtrxsum = mtrxsum+mtrx[n][m]
# After the end of two loops calculate the square root of the mtrxsum value
# using the sqrt() function
# and store this result in mtrxnormal variable.
mtrxnormal = math.sqrt(mtrxsum)
# Print the value of mtrxtrace which gives the value of the trace of the given matrix.
print('The trace value of the given matrix is :', mtrxtrace)
# Print the value of mtrxnormal which gives the value of the normal of the given matrix.
print('The normal value of the given matrix is :', mtrxnormal)

Output:

The trace value of the given matrix is : 15
The normal value of the given matrix is : 6.557438524302

Method #2: Using For loop (User Input)

Approach:

  • Import the math module using the import keyword.
  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Take a variable say mtrxtrace which stores the trace of the given matrix and initialize its value to 0.
  • Take a variable say mtrxsum which stores the sum of all elements of the matrix and initialize its value to 0.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the parent loop iterator value is equal to the inner loop iterator value using the if conditional statement(This is whether the element is diagonal element or not)
  • If it is true then add this value to mtrxtrace.
  • After the if conditional statement, Add the gvnmatrix[n][m] to the above-initialized mtrxsum and store it in the same variable mtrxsum.
  • After the end of two loops calculate the square root of the mtrxsum value using the sqrt() function and store this result in mtrxnormal variable.
  • Print the value of mtrxtrace which gives the value of the trace of the given matrix.
  • Print the value of mtrxnormal which gives the value of the normal of the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.
    mtrx.append(l)
# Take a variable say mtrxtrace which stores the trace of the given matrix
# and initialize its value to 0.
mtrxtrace = 0
# Take a variable say mtrxsum which stores the sum of all elements of the matrix
# and initialize its value to 0.
mtrxsum = 0
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the parent loop iterator value is equal to the inner loop iterator value
        # using the if conditional statement
        # (This is whether the element is diagonal element or not)
        if(n == m):
            # If it is true then add this value to mtrxtrace.
            mtrxtrace = mtrxtrace+mtrx[n][m]

        # After the if conditional statement,
        # Add the gvnmatrix[n][m] to the above-initialized mtrxsum
        # and store it in the same variable mtrxsum.
        mtrxsum = mtrxsum+mtrx[n][m]
# After the end of two loops calculate the square root of the mtrxsum value
# using the sqrt() function
# and store this result in mtrxnormal variable.
mtrxnormal = math.sqrt(mtrxsum)
# Print the value of mtrxtrace which gives the value of the trace of the given matrix.
print('The trace value of the given matrix is :', mtrxtrace)
# Print the value of mtrxnormal which gives the value of the normal of the given matrix.
print('The normal value of the given matrix is :', mtrxnormal)

Output:

Enter some random number of rows of the matrix = 4
Enter some random number of columns of the matrix = 4
Enter {4} elements of row {1} separated by spaces = 1 2 3 4
Enter {4} elements of row {2} separated by spaces = 7 5 8 6
Enter {4} elements of row {3} separated by spaces = 9 4 2 5
Enter {4} elements of row {4} separated by spaces = 1 1 1 1
The trace value of the given matrix is : 9
The normal value of the given matrix is : 7.745966692414834

Dive into numerous Python Programming Language Examples for practice and get the best out of the tutorial and learn python one step at a time.

Python Program to find the Normal and Trace of a Matrix Read More »

Program to Divide Two Numbers Using Recursion

Python Program to Divide Two Numbers Using Recursion

In the previous article, we have discussed Python Program to Multiply Two Numbers Using Recursion

Given two numbers and the task is to find the division of the given two numbers using recursion.

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.

Examples:

Example1:

Input:

Given First Number      =  18
Given Second Number =  9

Output:

The Division of { 18 / 9 } using recursion = 2

Example2:

Input:

Given First Number      = 48
Given Second Number = 6

Output:

The Division of { 48 / 6 } using recursion = 8

Program to Divide Two Numbers Using Recursion in Python

Below are the ways to find the division of the given two numbers using recursion :

Method #1: Using Recursion (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Pass the given two numbers as the arguments to recur_div function.
  • Create a recursive function to say recur_div which takes the two numbers as arguments and returns the division of the given two numbers using recursion.
  • Check if the first number is less than the second number using the if conditional statement.
  • If the statement is true, then return 0.
  • Return  1 + recur_div(fst_numb-secnd_numb, secnd_numb) {Recursive Logic}.
  • Print the division of the given two numbers using recursion.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say recur_div which takes the two numbers as arguments
# and returns the division of the given two numbers using recursion.


def recur_div(fst_numb, secnd_numb):
  # Check if the first number is less than the second number using the if conditional
  # statement.
    if fst_numb < secnd_numb:
        # If the statement is true, then return 0
        return 0
  # Return  1 + recur_div(fst_numb-secnd_numb, secnd_numb) {Recursive Logic}.
    return 1 + recur_div(fst_numb-secnd_numb, secnd_numb)


# Give the first number as static input and store it in a variable.
fst_numb = 18
# Give the second number as static input and store it in another variable.
secnd_numb = 9
# Pass the given two numbers as the arguments to recur_div function.
# Print the division of given two numbers using recursion.
print("The Division of {", fst_numb, "/", secnd_numb,
      "} using recursion =", recur_div(fst_numb, secnd_numb))

Output:

The Division of { 18 / 9 } using recursion = 2

Method #2: Using Recursion (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Pass the given two numbers as the arguments to the recur_div function.
  • Create a recursive function to say recur_div which takes the two numbers as arguments and returns the division of the given two numbers using recursion.
  • Check if the first number is less than the second number using the if conditional statement.
  • If the statement is true, then return 0.
  • Return  1 + recur_div(fst_numb-secnd_numb, secnd_numb) {Recursive Logic}.
  • Print the division of the given two numbers using recursion.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say recur_div which takes the two numbers as arguments
# and returns the division of the given two numbers using recursion.


def recur_div(fst_numb, secnd_numb):
  # Check if the first number is less than the second number using the if conditional
  # statement.
    if fst_numb < secnd_numb:
        # If the statement is true, then return 0
        return 0
  # Return  1 + recur_div(fst_numb-secnd_numb, secnd_numb) {Recursive Logic}.
    return 1 + recur_div(fst_numb-secnd_numb, secnd_numb)


# Give the first number as user input using the int(input()) function and 
# store it in a variable.
fst_numb = int(input("Enter some random number = "))
#Give the second number as user input using the int(input()) function and 
# store it in another variable.
secnd_numb = int(input("Enter some random number = "))
# Pass the given two numbers as the arguments to recur_div function.
# Print the division of given two numbers using recursion.
print("The Division of {", fst_numb, "/", secnd_numb,
      "} using recursion =", recur_div(fst_numb, secnd_numb))

Output:

Enter some random number = 45
Enter some random number = 9
The Division of { 45 / 9 } using recursion = 5

Explore more Example Python Programs with output and explanation and practice them for your interviews, assignments and stand out from the rest of the crowd.

Python Program to Divide Two Numbers Using Recursion Read More »

Program to Print Odd Numbers in Given Range Using Recursion

Python Program to Print Odd Numbers in Given Range Using Recursion

In the previous article, we have discussed Python Program to Print Even Numbers in Given Range Using Recursion

Given the upper limit and the task is to print the odd numbers in a given range (from 1 to given limit).

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.

Examples:

Example1:

Input:

 Given Upper Limit = 45

Output:

The Odd Numbers in a given range 1 and 45 are :
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45

Example2:

Input:

Given Upper Limit = 20

Output:

The Odd Numbers in a given range 1 and 20 are :
1 3 5 7 9 11 13 15 17 19

Program to Print Odd Numbers in Given Range Using Recursion in Python

Below are the ways to print the odd numbers in a given range in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the lower limit as 1 and store it in a variable.
  • Give the upper limit as static input and store it in another variable.
  • Pass the given lower and upper limits as the arguments to the odd_range function.
  • Create a recursive function to say odd_range which takes the given lower and upper limits as arguments and returns the odd numbers in a given range using recursion.
  • Check if the given lower limit value is greater than the upper limit using the if conditional statement.
  • If the statement is true, then return.
  • After the return statement, print the given lower limit separated by spaces.
  • Return odd_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
  • Print the Odd Numbers in a given lower and upper limit range.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say odd_range which takes the given lower and upper
# limits as arguments and returns the odd numbers in a given range using recursion.


def odd_range(gvnlowr_lmt, gvnuppr_lmt):
    # Check if the given lower limit value is greater than the upper limit using the if
    # conditional statement.
    if gvnlowr_lmt > gvnuppr_lmt:
        # If the statement is true, then return.
        return
    # After the return statement, print the given lower limit separated by spaces.
    print(gvnlowr_lmt, end=" ")
    # Return odd_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
    return odd_range(gvnlowr_lmt+2, gvnuppr_lmt)


# Give the lower limit as 1 and store it in a variable.
gvnlowr_lmt = 1
# Give the upper limit as static input and store it in another variable.
gvnuppr_lmt = 45
# Pass the given lower and upper limits as the arguments to odd_range function.
# Print the Odd Numbers in a given range.
print("The Odd Numbers in a given range",
      gvnlowr_lmt, "and", gvnuppr_lmt, "are :")
odd_range(gvnlowr_lmt, gvnuppr_lmt)

Output:

The Odd Numbers in a given range 1 and 45 are :
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45

Method #2: Using Recursion (User Input)

Approach:

  • Give the lower limit as 1 and store it in a variable.
  • Give the upper limit as user input using the int(input()) function and store it in another variable.
  • Pass the given lower and upper limits as the arguments to the odd_range function.
  • Create a recursive function to say odd_range which takes the given lower and upper limits as arguments and returns the odd numbers in a given range using recursion.
  • Check if the given lower limit value is greater than the upper limit using the if conditional statement.
  • If the statement is true, then return.
  • After the return statement, print the given lower limit separated by spaces.
  • Return odd_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
  • Print the Odd Numbers in a given lower and upper limit range.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say odd_range which takes the given lower and upper
# limits as arguments and returns the odd numbers in a given range using recursion.


def odd_range(gvnlowr_lmt, gvnuppr_lmt):
    # Check if the given lower limit value is greater than the upper limit using the if
    # conditional statement.
    if gvnlowr_lmt > gvnuppr_lmt:
        # If the statement is true, then return.
        return
    # After the return statement, print the given lower limit separated by spaces.
    print(gvnlowr_lmt, end=" ")
    # Return odd_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
    return odd_range(gvnlowr_lmt+2, gvnuppr_lmt)


# Give the lower limit as 1 and store it in a variable.
gvnlowr_lmt = 1
# Give the upper limit as user input using the int(input()) function and
# store it in another variable.
gvnuppr_lmt = int(input("Enter some random number = "))
# Pass the given lower and upper limits as the arguments to odd_range function.
# Print the Odd Numbers in a given range.
print("The Odd Numbers in a given range",
      gvnlowr_lmt, "and", gvnuppr_lmt, "are :")
odd_range(gvnlowr_lmt, gvnuppr_lmt)

Output:

Enter some random number = 20
The Odd Numbers in a given range 1 and 20 are :
1 3 5 7 9 11 13 15 17 19

If you are new to the Python Programming Language then practice using our Python Programming Examples for Beginners as our expert team has designed them from scratch.

Python Program to Print Odd Numbers in Given Range Using Recursion Read More »