Python

Program for Markov Matrix

Python Program for Markov Matrix

In the previous article, we have discussed Python Program for Sum of Middle Row and Column in Matrix

Markov Matrix:

The matrix where the sum of each row equals one.

Given a matrix, the task is to check if the given matrix is a Markov matrix or not.

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.

Examples:

Example1:

Input:

Given Matrix : 
0.5 0.5 0
0 0 1
1 0 0

Output:

Yes, the given matrix is a Markov Matrix

Example2:

Input:

Given Matrix : 
1 2 0
0 0.5 0.5
1 0 0

Output:

No, the given matrix is not a Markov Matrix

Program for Markov Matrix in Python

Below are the ways to check if the given matrix is a Markov matrix or not in python:

Method #1: Using For Loop (Static Input)

Approach:

  • 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.
  • Pass the given matrix as an argument to the chek_Markovmatrix function and check if the function returns true or false using the if conditional statement.
  • If it is true then print  “Yes, the given matrix is a Markov Matrix”.
  • Else print “No, the given matrix is not a Markov Matrix”.
  • Create a function to say chek_Markovmatrix which takes the given matrix as an argument and returns True or false.
  • Loop till the given number of rows using the For loop.
  • Take a variable to say row_summ and initialize its value to 0.
  • Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Add mtrx[p][q] to the above row_summ (where p is the iterator value of the parent for loop and q is the iterator value of the inner forloop).
  • Store it in the same variable row_summ
  • Check if the value of row_summ is not equal to 1 using the if conditional statement.
  • If it is true then return false.
  • Return True.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say chek_Markovmatrix which takes the given matrix as an argument
# and returns True or false.


def chek_Markovmatrix(mtrx):

   # Loop till the given number of rows using the For loop.
    for p in range(mtrxrows):
        # Take a variable to say row_summ and initialize its value to 0.

        row_summ = 0
        # Inside the For loop, Iterate till the given number of rows using another Nested
        # For loop (Inner For loop).
        for q in range(mtrxrows):
           # Add mtrx[p][q] to the above row_summ (where p is the iterator value of the
           # parent for loop and q is the iterator value of the inner forloop).
           # Store it in the same variable row_summ
            row_summ = row_summ + mtrx[p][q]
        # Check if the value of row_summ is not equal to 1 using the if conditional
        # statement.
        if (row_summ != 1):
          # If it is true then return false.
            return False
        # Return True.
    return True


# Give the matrix as static input and store it in a variable.
mtrx = [[0.5, 0.5, 0], [0, 0, 1], [1, 0, 0]]
# 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])
# Pass the given matrix as an argument to the chek_Markovmatrix function and check if
# the function returns true or false using the if conditional statement.
if (chek_Markovmatrix(mtrx)):
  # If it is true then print  "Yes, the given matrix is a Markov Matrix".
    print("Yes, the given matrix is a Markov Matrix")
else:
  # Else print "No, the given matrix is not a Markov Matrix".
    print("No, the given matrix is not a Markov Matrix")

Output:

Yes, the given matrix is a Markov Matrix

Method #2: Using For loop (User Input)

Approach:

  • 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(), float(), split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Pass the given matrix as an argument to the chek_Markovmatrix function and check if the function returns true or false using the if conditional statement.
  • If it is true then print  “Yes, the given matrix is a Markov Matrix”.
  • Else print “No, the given matrix is not a Markov Matrix”.
  • Create a function to say chek_Markovmatrix which takes the given matrix as an argument and returns True or false.
  • Loop till the given number of rows using the For loop.
  • Take a variable to say row_summ and initialize its value to 0.
  • Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Add mtrx[p][q] to the above row_summ (where p is the iterator value of the parent for loop and q is the iterator value of the inner for loop).
  • Store it in the same variable row_summ
  • Check if the value of row_summ is not equal to 1 using the if conditional statement.
  • If it is true then return false.
  • Return True.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say chek_Markovmatrix which takes the given matrix as an argument
# and returns True or false.


def chek_Markovmatrix(mtrx):

   # Loop till the given number of rows using the For loop.
    for p in range(mtrxrows):
        # Take a variable to say row_summ and initialize its value to 0.

        row_summ = 0
        # Inside the For loop, Iterate till the given number of rows using another Nested
        # For loop (Inner For loop).
        for q in range(mtrxrows):
           # Add mtrx[p][q] to the above row_summ (where p is the iterator value of the
           # parent for loop and q is the iterator value of the inner forloop).
           # Store it in the same variable row_summ
            row_summ = row_summ + mtrx[p][q]
        # Check if the value of row_summ is not equal to 1 using the if conditional
        # statement.
        if (row_summ != 1):
          # If it is true then return false.
            return False
        # Return True.
    return True


# 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(),float(),split() functions and store it in a variable.
    l = list(map(float, 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)
    
# Pass the given matrix as an argument to the chek_Markovmatrix function and check if
# the function returns true or false using the if conditional statement.
if (chek_Markovmatrix(mtrx)):
  # If it is true then print  "Yes, the given matrix is a Markov Matrix".
    print("Yes, the given matrix is a Markov Matrix")
else:
  # Else print "No, the given matrix is not a Markov Matrix".
    print("No, the given matrix is not a Markov Matrix")

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 1 2 0
Enter {3} elements of row {2} separated by spaces = 0 0.5 0.5
Enter {3} elements of row {3} separated by spaces = 1 0 0
No, the given matrix is not a Markov Matrix

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 for Markov Matrix Read More »

Program for Sum of Middle Row and Column in Matrix

Python Program for Sum of Middle Row and Column in Matrix

In the previous article, we have discussed Python Program to Interchange Elements of First and Last Rows in Matrix

Given a matrix and the task is to get the sum of middle row elements and the middle column elements of a given matrix.

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.

Examples:

Example1:

Input:

Given Matrix :
4 2 0
4 2 3
5 6 9

Output:

The sum of middle row elements of the above given matrix =  9
The sum of middle column elements of the above given matrix =  10

Example2:

Input:

Given Matrix :
0 1 3
4 5 6
8 2 1

Output:

The sum of middle row elements of the above given matrix = 15
The sum of middle column elements of the above given matrix = 8

Program for Sum of Middle Row and Column in Matrix in Python

Below are the ways to get the sum of middle row elements and the middle column elements of a given matrix in python:

Method #1: Using For Loop (Static Input)

Approach:

  • 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 to say middlrow_sum and initialize its value to 0.
  • Take a variable to say middlcol_sum and initialize its value to 0.
  • Loop till the given number of rows using the For loop.
  • Inside the for loop, add mtrx[mtrxrows // 2][itr] to the above-initialized middlrow_sum where itr is the iterator value of the for loop.
  • Print the sum of the middle row elements of the given matrix.
  • Loop till the given number of rows using the For loop.
  • Inside the for loop, add mtrx[itr][mtrxrows // 2]  to the above-initialized middlcol_sum where itr is the iterator value of the for loop.
  • Print the sum of the middle column elements of the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[4, 2, 0], [4, 2, 3], [5, 6, 9]]
# 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 to say middlrow_sum and initialize its value to 0.
middlrow_sum = 0
# Take a variable to say middlcol_sum and initialize its value to 0.
middlcol_sum = 0
# Loop till the given number of rows using the For loop.
for itr in range(mtrxrows):
  # Inside the for loop, add mtrx[mtrxrows // 2][itr] to the above-initialized middlrow_sum
  # where itr is the iterator value of the for loop.

    middlrow_sum += mtrx[mtrxrows // 2][itr]
# Print the sum of the middle row elements of the given matrix.
print("The sum of middle row elements of the above given matrix = ",
      middlrow_sum)
# Loop till the given number of rows using the For loop.
for itr in range(mtrxrows):
  # Inside the for loop, add mtrx[itr][mtrxrows // 2]  to the above-initialized middlcol_sum
  # where itr is the iterator value of the for loop.

    middlcol_sum += mtrx[itr][mtrxrows // 2]
# Print the sum of the middle column elements of the given matrix.
print("The sum of middle column elements of the above given matrix = ",
      middlcol_sum)

Output:

The sum of middle row elements of the above given matrix =  9
The sum of middle column elements of the above given matrix =  10

Method #2: Using For loop (User Input)

Approach:

  • 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 to say middlrow_sum and initialize its value to 0.
  • Take a variable to say middlcol_sum and initialize its value to 0.
  • Loop till the given number of rows using the For loop.
  • Inside the for loop, add mtrx[mtrxrows // 2][itr] to the above-initialized middlrow_sum where itr is the iterator value of the for loop.
  • Print the sum of the middle row elements of the given matrix.
  • Loop till the given number of rows using the For loop.
  • Inside the for loop, add mtrx[itr][mtrxrows // 2]  to the above-initialized middlcol_sum where itr is the iterator value of the for loop.
  • Print the sum of the middle column elements of the given matrix.
  • The Exit of the Program.

Below is the implementation:

# 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 to say middlrow_sum and initialize its value to 0.
middlrow_sum = 0
# Take a variable to say middlcol_sum and initialize its value to 0.
middlcol_sum = 0
# Loop till the given number of rows using the For loop.
for itr in range(mtrxrows):
  # Inside the for loop, add mtrx[mtrxrows // 2][itr] to the above-initialized middlrow_sum
  # where itr is the iterator value of the for loop.

    middlrow_sum += mtrx[mtrxrows // 2][itr]
# Print the sum of the middle row elements of the given matrix.
print("The sum of middle row elements of the above given matrix = ",
      middlrow_sum)
# Loop till the given number of rows using the For loop.
for itr in range(mtrxrows):
  # Inside the for loop, add mtrx[itr][mtrxrows // 2]  to the above-initialized middlcol_sum
  # where itr is the iterator value of the for loop.

    middlcol_sum += mtrx[itr][mtrxrows // 2]
# Print the sum of the middle column elements of the given matrix.
print("The sum of middle column elements of the above given matrix = ",
      middlcol_sum)

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 0 1 3
Enter {3} elements of row {2} separated by spaces = 4 5 6
Enter {3} elements of row {3} separated by spaces = 8 2 1
The sum of middle row elements of the above given matrix = 15
The sum of middle column elements of the above given matrix = 8

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 for Sum of Middle Row and Column in Matrix Read More »

Program to Remove Odd Occurring Characters from the String

Python Program to Remove Odd Occurring Characters from the String

In the previous article, we have discussed Python Program for Given Two Numbers a and b Find all x Such that a % x = b

Given a string and the task is to remove all the odd occurring characters from the given string.

Examples:

Example1:

Input:

Given String = "goodmorning"

Output:

The given string { goodmorning } after removing odd frequency elements is : gnng

Example2:

Input:

Given String = "thisisbtechgeeks"

Output:

The given string { thisisbtechgeeks } after removing odd frequency elements is : thiith

Program to Remove Odd Occurring Characters from the String in Python.

Below are the ways to remove all the odd occurring characters from the given string in python:

Method #1: Using Dictionary (Hashing, Static Input)

Approach:

  • Take a dictionary and initialize it to empty using the {} or dict() say freqncyDictionary.
  • Give the string as static input and store it in a variable.
  • Loop in the given string using the For loop.
  • Inside the For loop, Check if the string character is present in the dictionary or not using the if conditional statement and ‘in’ keyword.
  • If the above condition is true then increment the count of the string character in the dictionary by 1.
  • Else initialize the dictionary with the string character as key and value as 1.
  • Take a string that stores all the characters which are not occurring odd a number of times and initialize it to null string using “or str()
  • loop in the given string using the for loop.
  • Check if the character has an even frequency by checking the value of that character in the frequency dictionary we check using the if conditional statement.
  • If it is true then concatenate this character to modifd_string using string concatenation.
  • Print the modifd_string string.
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it to empty
# using the {} or dict() say freqncyDictionary.
freqncyDictionary = {}
# Give the string as static input and store it in a variable
gvnstrng = "goodmorning"
# Loop in the given string using the For loop.
for i in gvnstrng:
        # Inside the For loop,
    # Check if the string character is present in the dictionary
    # or not using the if conditional statement and 'in' keyword.
    if i in freqncyDictionary.keys():
                # If it is true then increment the count of the string character
        # in the dictionary by 1.
        freqncyDictionary[i] = freqncyDictionary[i]+1
    # Else initialize the dictionary with the string character as key and value as 1.
    else:
        freqncyDictionary[i] = 1
# Take a string which stores all the characters which are not occuring odd number
# of times and initialize it to null string using "" or str()
modifd_string = ""
# loop in the given string using the for loop
for charac in gvnstrng:

        # check if the character has even frequency by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] % 2 == 0):
        # if it is true then concatenate this character to modifd_string using string concatenation
        modifd_string = modifd_string+charac


# print the modifd_string string
print('The given string {', gvnstrng,
      '} after removing odd frequency elements is :', modifd_string)

Output:

The given string { goodmorning } after removing odd frequency elements is : gnng

Method #2: Using Dictionary (Hashing, User Input)

Approach:

  • Take a dictionary and initialize it to empty using the {} or dict() say freqncyDictionary.
  • Give the string as the user input using the input() function and store it in a variable.
  • Loop in the given string using the For loop.
  • Inside the For loop, Check if the string character is present in the dictionary or not using the if conditional statement and ‘in’ keyword.
  • If the above condition is true then increment the count of the string character in the dictionary by 1.
  • Else initialize the dictionary with the string character as key and value as 1.
  • Take a string that stores all the characters which are not occurring odd a number of times and initialize it to null string using “or str()
  • loop in the given string using the for loop.
  • Check if the character has an even frequency by checking the value of that character in the frequency dictionary we check using the if conditional statement.
  • If it is true then concatenate this character to modifd_string using string concatenation.
  • Print the modifd_string string.
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it to empty
# using the {} or dict() say freqncyDictionary.
freqncyDictionary = {}
# Give the string as the user input using the input() function and store it in a variable.
gvnstrng = input("Enter some random string = ")
# Loop in the given string using the For loop.
for i in gvnstrng:
        # Inside the For loop,
    # Check if the string character is present in the dictionary
    # or not using the if conditional statement and 'in' keyword.
    if i in freqncyDictionary.keys():
                # If it is true then increment the count of the string character
        # in the dictionary by 1.
        freqncyDictionary[i] = freqncyDictionary[i]+1
    # Else initialize the dictionary with the string character as key and value as 1.
    else:
        freqncyDictionary[i] = 1
# Take a string which stores all the characters which are not occuring odd number
# of times and initialize it to null string using "" or str()
modifd_string = ""
# loop in the given string using the for loop
for charac in gvnstrng:

        # check if the character has even frequency by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] % 2 == 0):
        # if it is true then concatenate this character to modifd_string using string concatenation
        modifd_string = modifd_string+charac


# print the modifd_string string
print('The given string {', gvnstrng,
      '} after removing odd frequency elements is :', modifd_string)

Output:

Enter some random string = thisisbtechgeeks
The given string { thisisbtechgeeks } after removing odd frequency elements is : thiith

Method #3: 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 characters using the Counter() function which returns the element and its frequency as key-value pair  and store this dictionary in a variable(say freqncyDictionary)
  • Take a string that stores all the characters which are not occurring odd a number of times and initialize it to null string using “or str()
  • loop in the given string using the for loop.
  • Check if the character has an even frequency by checking the value of that character in the frequency dictionary we check using the if conditional statement.
  • If the above condition is true then concatenate this character to modifd_string using string concatenation.
  • Print the modifd_string string.
  • 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
gvnstrng = "goodmorning"
# Calculate the frequency of all the given string characters using the Counter()
# function which returns the element and its frequency as key-value pair
# and store this dictionary in a variable(say freqncyDictionary)
freqncyDictionary = Counter(gvnstrng)
# Take a string which stores all the characters which are not occuring odd number
# of times and initialize it to null string using "" or str()
modifd_string = ""
# loop in the given string using the for loop
for charac in gvnstrng:

        # check if the character has even frequency by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] % 2 == 0):
        # if it is true then concatenate this character to modifd_string using string concatenation
        modifd_string = modifd_string+charac


# print the modifd_string string
print('The given string {', gvnstrng,
      '} after removing odd frequency elements is :', modifd_string)

Output:

The given string { goodmorning } after removing odd frequency elements is : gnng

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

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string as the user input using the input() function and store it in a variable.
  • Calculate the frequency of all the given string characters using the Counter() function which returns the element and its frequency as key-value pair  and store this dictionary in a variable(say freqncyDictionary)
  • Take a string that stores all the characters which are not occurring odd a number of times and initialize it to null string using “or str()
  • loop in the given string using the for loop.
  • Check if the character has an even frequency by checking the value of that character in the frequency dictionary we check using the if conditional statement.
  • If the above condition is true then concatenate this character to modifd_string using string concatenation.
  • Print the modifd_string string.
  • 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
gvnstrng = input("Enter some random string = ")
# Calculate the frequency of all the given string characters using the Counter()
# function which returns the element and its frequency as key-value pair
# and store this dictionary in a variable(say freqncyDictionary)
freqncyDictionary = Counter(gvnstrng)
# Take a string which stores all the characters which are not occuring odd number
# of times and initialize it to null string using "" or str()
modifd_string = ""
# loop in the given string using the for loop
for charac in gvnstrng:

        # check if the character has even frequency by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] % 2 == 0):
        # if it is true then concatenate this character to modifd_string using string concatenation
        modifd_string = modifd_string+charac


# print the modifd_string string
print('The given string {', gvnstrng,
      '} after removing odd frequency elements is :', modifd_string)

Output:

Enter some random string = thisisbtechgeeks
The given string { thisisbtechgeeks } after removing odd frequency elements is : thiith

Remediate your knowledge gap by attempting the Python Code Examples regularly and understand the areas of need and work on them.

Python Program to Remove Odd Occurring Characters from the String Read More »

Program to Swap Upper Diagonal Elements with Lower Diagonal Elements of Matrix

Python Program to Swap Upper Diagonal Elements with Lower Diagonal Elements of Matrix

In the previous article, we have discussed Python Program for Frequencies of Even and Odd Numbers in a Matrix

Given a square matrix, the task is to swap the upper diagonal elements and lower diagonal elements of a given matrix.

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.

Diagonal Matrix:

The entries outside the main diagonal of a diagonal matrix are all 0; the word usually refers to square matrices.

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.

Examples:

Example1:

Input:

Given Matrix :
10 20 30 
45 60 70
11 12 13

Output:

The Matrix after swapping the upper diagonal and lower diagonal elements is:
10 45 11 
20 60 12 
30 70 13

Example2:

Input:

Given Matrix :
3 5 1 
4 2 0
2 6 4

Output:

The Matrix after swapping the upper diagonal and lower diagonal elements is:
3 4 2 
5 2 6 
1 0 4

Program to Swap Upper Diagonal Elements with Lower Diagonal Elements of Matrix in Python

Below are the ways to swap the upper diagonal elements and lower diagonal elements of a given matrix in python:

Method #1: Using For Loop (Static Input)

Approach:

  • 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.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, iterate from the iterator value +1 of the parent for loop to the given number of rows using another Nested For loop(Inner For loop).
  • Swap mtrx[itor][k], mtrx[k][itor] using the comma(,) operator ( where itor is the iterator value of the parent for loop and k is the iterator value of the inner for loop).
  • Loop till the given number of rows using the For loop.
  •  Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Print the element of the matrix by printing gvnmatrix[n][m] value where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[10, 20, 30], [45, 60, 70], [11, 12, 13]]
# 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])
# Loop till the given number of rows using the For loop.
for itor in range(0, mtrxrows):
   # Inside the For loop, iterate from the iterator value +1 of the parent for loop to the
   # given number of rows using another Nested For loop(Inner For loop).

    for k in range(itor + 1, mtrxrows):
      # Swap mtrx[itor][k], mtrx[k][itor] using the comma(,) operator ( where itor is the
      # iterator value of the parent for loop and k is the iterator value
      # of the inner for loop).

        mtrx[itor][k], mtrx[k][itor] = mtrx[k][itor], mtrx[itor][k]

print("The Matrix after swapping the upper diagonal and lower diagonal elements is:")
# 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 rows using another
    # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Print the element of the matrix by printing gvnmatrix[n][m] value
        # where n is the iterator value of the parent For loop and m is the iterator
        # value of the inner For loop.
        print(mtrx[n][m], end=' ')
    print()

Output:

The Matrix after swapping the upper diagonal and lower diagonal elements is:
10 45 11 
20 60 12 
30 70 13

Method #2: Using For loop (User Input)

Approach:

  • 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.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, iterate from the iterator value +1 of the parent for loop to the given number of rows using another Nested For loop(Inner For loop).
  • Swap mtrx[itor][k], mtrx[k][itor] using the comma(,) operator ( where itor is the iterator value of the parent for loop and k is the iterator value of the inner for loop).
  • Loop till the given number of rows using the For loop.
  •  Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Print the element of the matrix by printing gvnmatrix[n][m] value where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • The Exit of the Program.

Below is the implementation:

# 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)

# Loop till the given number of rows using the For loop.
for itor in range(0, mtrxrows):
   # Inside the For loop, iterate from the iterator value +1 of the parent for loop to the
   # given number of rows using another Nested For loop(Inner For loop).

    for k in range(itor + 1, mtrxrows):
      # Swap mtrx[itor][k], mtrx[k][itor] using the comma(,) operator ( where itor is the
      # iterator value of the parent for loop and k is the iterator value
      # of the inner for loop).

        mtrx[itor][k], mtrx[k][itor] = mtrx[k][itor], mtrx[itor][k]

print("The Matrix after swapping the upper diagonal and lower diagonal elements is:")
# 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 rows using another
    # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Print the element of the matrix by printing gvnmatrix[n][m] value
        # where n is the iterator value of the parent For loop and m is the iterator
        # value of the inner For loop.
        print(mtrx[n][m], end=' ')
    print()

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 3 5 1 
Enter {3} elements of row {2} separated by spaces = 4 2 0
Enter {3} elements of row {3} separated by spaces = 2 6 4
The Matrix after swapping the upper diagonal and lower diagonal elements is:
3 4 2 
5 2 6 
1 0 4

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 Swap Upper Diagonal Elements with Lower Diagonal Elements of Matrix Read More »

Program for Frequencies of Even and Odd Numbers in a Matrix

Python Program for Frequencies of Even and Odd Numbers in a Matrix

In the previous article, we have discussed Python Program to Check Diagonally Dominant Matrix

Given a square matrix, the task is to get the frequency of even numbers and odd numbers of a 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.

Examples:

Example1:

Input:

Given Matrix :
9 0 2
7 5 6
7 1 9

Output:

The odd number frequency of the given matrix = 6
The even number frequency of the given matrix  3

Example2:

Input:

Given Matrix :
5 3 2
8 4 1
7 2 3

Output:

 The odd number frequency of the given matrix = 5
The even number frequency of the given matrix 4

Program for Frequencies of Even and Odd Numbers in a Matrix

Below are the ways to get the frequency of even numbers and odd numbers of a given matrix in python:

Method #1: Using For Loop (Static Input)

Approach:

  • 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 to say evnnum_freqcy and initialize its value to 0.
  • Take another variable to say oddnum_freqcy 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 mtrx[n][m] is even using the if conditional statement (where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.).
  • If it is true, then increment the value of above evnnum_freqcy by 1.
  • Else increment the value of above oddnum_freqcy by 1.
  • Print the frequency of even numbers and odd numbers of a given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[9, 0, 2],
        [7, 5, 6],
        [7, 1, 9]]
# 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 to say evnnum_freqcy and initialize its value to 0.
evnnum_freqcy = 0
# Take another variable to say oddnum_freqcy and initialize its value to 0.
oddnum_freqcy = 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 mtrx[n][m] is even using the if conditional statement (where n is the
        # iterator value of the parent For loop and m is the iterator value of the
        # inner For loop.).

        if ((mtrx[n][m] % 2) == 0):
         # If it is true, then increment the value of above evnnum_freqcy by 1.
            evnnum_freqcy += 1
        else:
           # Else increment the value of above oddnum_freqcy by 1.
            oddnum_freqcy += 1
# Print the frequency of even numbers and odd numbers of a given matrix.
print(" The odd number frequency of the given matrix =", oddnum_freqcy)
print(" The even number frequency of the given matrix ", evnnum_freqcy)

Output:

The odd number frequency of the given matrix = 6
 The even number frequency of the given matrix  3

Method #2: Using For loop (User Input)

Approach:

  • 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 to say evnnum_freqcy and initialize its value to 0.
  • Take another variable to say oddnum_freqcy 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 mtrx[n][m] is even using the if conditional statement (where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.).
  • If it is true, then increment the value of above evnnum_freqcy by 1.
  • Else increment the value of above oddnum_freqcy by 1.
  • Print the frequency of even numbers and odd numbers of a given matrix.
  • The Exit of the Program.

Below is the implementation:

# 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 to say evnnum_freqcy and initialize its value to 0.
evnnum_freqcy = 0
# Take another variable to say oddnum_freqcy and initialize its value to 0.
oddnum_freqcy = 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 mtrx[n][m] is even using the if conditional statement (where n is the
        # iterator value of the parent For loop and m is the iterator value of the
        # inner For loop.).

        if ((mtrx[n][m] % 2) == 0):
         # If it is true, then increment the value of above evnnum_freqcy by 1.
            evnnum_freqcy += 1
        else:
           # Else increment the value of above oddnum_freqcy by 1.
            oddnum_freqcy += 1
# Print the frequency of even numbers and odd numbers of a given matrix.
print(" The odd number frequency of the given matrix =", oddnum_freqcy)
print(" The even number frequency of the given matrix ", evnnum_freqcy)

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 5 3 2
Enter {3} elements of row {2} separated by spaces = 8 4 1
Enter {3} elements of row {3} separated by spaces = 7 2 3
The odd number frequency of the given matrix = 5
The even number frequency of the given matrix 4

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 for Frequencies of Even and Odd Numbers in a Matrix Read More »

Program to Check Diagonally Dominant Matrix

Python Program to Check Diagonally Dominant Matrix

In the previous article, we have discussed Python Program to Check if a Pair with Given Product Exists in a Matrix

Given a square matrix and the task is to check whether the given matrix is a diagonally dominant matrix or not.

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.

Diagonally Dominant Matrix :

A square matrix is said to be diagonally dominating in mathematics if the magnitude of the diagonal entry in a row is greater than or equal to the sum of the magnitudes of all the other (non-diagonal) values in that row for each row of the matrix.

Examples:

Example1:

Input:

Given Matrix : 
5 1 3
2 7 1
4 0 9

Output:

Yes, the given matrix is a diagonally dominant matrix

Example2:

Input:

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

Output:

No, the given matrix is not a diagonally dominant matrix

Program to Check Diagonally Dominant Matrix in Python

Below are the ways to check whether the given matrix is a diagonally dominant matrix or not in python:

Method #1: Using For Loop (Static Input)

Approach:

  • 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.
  • Create a function to say checkdiagnolydominant_matx() which takes the given matrix and the number of rows of the given matrix as the arguments and returns true or false.
  • Inside the function, Loop till the given number of rows using the For loop.
  • Take a variable to say rslt_summ and initialize its value to 0.
  • Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Add the absolute of mtrx[n][m] to the above-initialized rslt_summ and store it in the same variable.
  • Remove the diagonal element by subtracting the abs(mtrx[n][n]) from the rslt_summ and store it in the same variable.
  • Check if the abs(mtrx[n][n]) (diagonal element) is less than the rslt_summ(Which is the sum of non diagonal elements) using the if conditional statement.
  • If it is true, then return False.
  • Return True.
  • Pass the given matrix and the number of rows of the given matrix as the arguments to the checkdiagnolydominant_matx() function and check if returns true or false using the if conditional statement.
  • If it is true, print “Yes, the given matrix is a diagonally dominant matrix”.
  • Else print “No, the given matrix is not a diagonally dominant matrix”.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say checkdiagnolydominant_matx() which takes the given matrix
# and the number of rows of the given matrix as the arguments and returns true or false


def checkdiagnolydominant_matx(mtrx, mtrxrows):
    # Inside the function, Loop till the given number of rows using the For loop.
    for n in range(0, mtrxrows):
       # Take a variable to say rslt_summ and initialize its value to 0.
        rslt_summ = 0
        # Inside the For loop, Iterate till the given number of rows using another
        # Nested For loop(Inner For loop).

        for m in range(0, mtrxrows):
          # Add the absolute of mtrx[n][m] to the above-initialized rslt_summ and store
          # it in  the same variable.

            rslt_summ = rslt_summ + abs(mtrx[n][m])
       # Remove the diagonal element by subtracting the abs(mtrx[n][n]) from the rslt_summ and
       # store it in the same variable.
        rslt_summ = rslt_summ - abs(mtrx[n][n])
        # Check if the abs(mtrx[n][n]) (diagonal element) is less than the rslt_summ
        # (Which is the #sum of non diagonal elements) using the if conditional statement.
        if (abs(mtrx[n][n]) < rslt_summ):
          # If it is true, then return False.
            return False
    # Return True.
    return True


# Give the matrix as static input and store it in a variable.
mtrx = [[5, 1, 3], [2, 7, 1], [4, 0, 9]]
# 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])
# Pass the given matrix and the number of rows of the given matrix as the arguments
# to the checkdiagnolydominant_matx() function and check if returns true or false
# using the if conditional statement.
if((checkdiagnolydominant_matx(mtrx, mtrxrows))):
  # If it is true, print "Yes, the given matrix is a diagonally dominant matrix".
    print("Yes, the given matrix is a diagonally dominant matrix")
else:
  # Else print "No, the given matrix is not a diagonally dominant matrix".
    print("No, the given matrix is not a diagonally dominant matrix")

Output:

Yes, the given matrix is a diagonally dominant matrix

Method #2: Using For loop (User Input)

Approach:

  • 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.
  • Create a function to say checkdiagnolydominant_matx() which takes the given matrix and the number of rows of the given matrix as the arguments and returns true or false.
  • Inside the function, Loop till the given number of rows using the For loop.
  • Take a variable to say rslt_summ and initialize its value to 0.
  • Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Add the absolute of mtrx[n][m] to the above-initialized rslt_summ and store it in the same variable.
  • Remove the diagonal element by subtracting the abs(mtrx[n][n]) from the rslt_summ and store it in the same variable.
  • Check if the abs(mtrx[n][n]) (diagonal element) is less than the rslt_summ(Which is the sum of non diagonal elements) using the if conditional statement.
  • If it is true, then return False.
  • Return True.
  • Pass the given matrix and the number of rows of the given matrix as the arguments to the checkdiagnolydominant_matx() function and check if returns true or false using the if conditional statement.
  • If it is true, print “Yes, the given matrix is a diagonally dominant matrix”.
  • Else print “No, the given matrix is not a diagonally dominant matrix”.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say checkdiagnolydominant_matx() which takes the given matrix
# and the number of rows of the given matrix as the arguments and returns true or false


def checkdiagnolydominant_matx(mtrx, mtrxrows):
    # Inside the function, Loop till the given number of rows using the For loop.
    for n in range(0, mtrxrows):
       # Take a variable to say rslt_summ and initialize its value to 0.
        rslt_summ = 0
        # Inside the For loop, Iterate till the given number of rows using another
        # Nested For loop(Inner For loop).

        for m in range(0, mtrxrows):
          # Add the absolute of mtrx[n][m] to the above-initialized rslt_summ and store
          # it in  the same variable.

            rslt_summ = rslt_summ + abs(mtrx[n][m])
       # Remove the diagonal element by subtracting the abs(mtrx[n][n]) from the rslt_summ and
       # store it in the same variable.
        rslt_summ = rslt_summ - abs(mtrx[n][n])
        # Check if the abs(mtrx[n][n]) (diagonal element) is less than the rslt_summ
        # (Which is the #sum of non diagonal elements) using the if conditional statement.
        if (abs(mtrx[n][n]) < rslt_summ):
          # If it is true, then return False.
            return False
    # Return True.
    return True


# 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)
if((checkdiagnolydominant_matx(mtrx, mtrxrows))):
  # If it is true, print "Yes, the given matrix is a diagonally dominant matrix".
    print("Yes, the given matrix is a diagonally dominant matrix")
else:
  # Else print "No, the given matrix is not a diagonally dominant matrix".
    print("No, the given matrix is not a diagonally dominant matrix")

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 1 3 5
Enter {3} elements of row {2} separated by spaces = 2 4 6
Enter {3} elements of row {3} separated by spaces = 7 8 9
No, the given matrix is not a diagonally dominant matrix

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 Check Diagonally Dominant Matrix Read More »

Program to Check if a Pair with Given Product Exists in a Matrix

Python Program to Check if a Pair with Given Product Exists in a Matrix

In the previous article, we have discussed Python Program to Count Frequency of k in a Matrix of Size n Where Matrix(i, j) = i+j

Given a matrix and the product value k, the task is to check whether the pair with the given product value exists in the given matrix or not.

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.

Examples:

Example1:

Input:

Given Matrix : 
1 5 4
8 6 1
6 2 4

Output:

Yes, the pair with the given product value k exists in the given matrix

Example2:

Input:

Given Matrix : 
5 2 1
4 6 3
1 7 1

Output:

No, the pair with the given product value k does not exist in the given matrix

Program to Check if a Pair with Given Product Exists in a Matrix in Python

Below are the ways to check whether the pair with the given product value exists in the given matrix or not.

Method #1: Using For Loop (Static Input)

Approach:

  • 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.
  • Give the k value as static input and store it in another variable.
  • Create a function to say CheckPairwith_prodctK() which takes the given matrix and given product k value as the arguments and returns true or false.
  • Inside the function, take a new empty list and store it in another variable.
  • 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 value of given k modulus mtrx[n][m] is equal to 0 and given k value divided by mtrx[n[m] is present in the above declared new list using the if conditional statement.
  • If it is true, then return true.
  • Else append mtrx[n][m] to the above new list using the append() function.
  • Pass the given matrix and the given k value as the arguments to the CheckPairwith_prodctK() function and check if it returns true or false using the if conditional statement.
  • If it is true, then print “Yes, the pair with the given product value k exists in the given matrix”.
  • Else print “No, the pair with the given product value k does not exist in the given matrix”.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say CheckPairwith_prodctK() which takes the given matrix and
# given product k value as the arguments and returns true or false.


def CheckPairwith_prodctK(mtrx, gvn_k_val):
        # Inside the function, take a new empty list and store it in another variable.
    new_lst = []
    # 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 value of given k modulus mtrx[n][m] is equal to 0 and given k
          # value divided by mtrx[n[m] is present in the above declared new list using
          # the if # conditional statement.
            if ((gvn_k_val % mtrx[n][m] == 0) and
                    (gvn_k_val // mtrx[n][m]) in new_lst):
                # If it is true, then return true.
                return True
                # Else append mtrx[n][m] to the above new list using the append() function.
            else:
                new_lst.append(mtrx[n][m])


# Give the matrix as static input and store it in a variable.
mtrx = [[1, 5, 4], [8, 6, 1], [6, 2, 4]]
# 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])
# Give the k value as static input and store it in another variable.
gvn_k_val = 30
# Pass the given matrix and the given k value as the arguments to the
# CheckPairwith_prodctK() function and check if it returns true or false using
# the if conditional statement.
if (CheckPairwith_prodctK(mtrx, gvn_k_val)):
        # If it is true, then print "Yes, the pair with the given product value k exists in
        # the given matrix".
    print("Yes, the pair with the given product value k exists in the given matrix")

else:
    # Else print "No, the pair with the given product value k does not exist in the given
        # matrix".
    print("No, the pair with the given product value k does not exist in the given matrix")

Output:

Yes, the pair with the given product value k exists in the given matrix

Method #2: Using For loop (User Input)

Approach:

  • 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.
  • Give the k value as user input using the int(input()) function and store it in another variable.
  • Create a function to say CheckPairwith_prodctK() which takes the given matrix and given product k value as the arguments and returns true or false.
  • Inside the function, take a new empty list and store it in another variable.
  • 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 value of given k modulus mtrx[n][m] is equal to 0 and given k value divided by mtrx[n[m] is present in the above declared new list using the if conditional statement.
  • If it is true, then return true.
  • Else append mtrx[n][m] to the above new list using the append() function.
  • Pass the given matrix and the given k value as the arguments to the CheckPairwith_prodctK() function and check if it returns true or false using the if conditional statement.
  • If it is true, then print “Yes, the pair with the given product value k exists in the given matrix”.
  • Else print “No, the pair with the given product value k does not exist in the given matrix”.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say CheckPairwith_prodctK() which takes the given matrix and
# given product k value as the arguments and returns true or false.


def CheckPairwith_prodctK(mtrx, gvn_k_val):
        # Inside the function, take a new empty list and store it in another variable.
    new_lst = []
    # 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 value of given k modulus mtrx[n][m] is equal to 0 and given k
          # value divided by mtrx[n[m] is present in the above declared new list using
          # the if # conditional statement.
            if ((gvn_k_val % mtrx[n][m] == 0) and
                    (gvn_k_val // mtrx[n][m]) in new_lst):
                # If it is true, then return true.
                return True
                # Else append mtrx[n][m] to the above new list using the append() function.
            else:
                new_lst.append(mtrx[n][m])


# 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)
    
# Give the k value as user input using the int(input()) function and
# store it in another variable.
gvn_k_val = int(input("Enter some random number = "))
# Pass the given matrix and the given k value as the arguments to the
# CheckPairwith_prodctK() function and check if it returns true or false using
# the if conditional statement.
if (CheckPairwith_prodctK(mtrx, gvn_k_val)):
        # If it is true, then print "Yes, the pair with the given product value k exists in
        # the given matrix".
    print("Yes, the pair with the given product value k exists in the given matrix")

else:
    # Else print "No, the pair with the given product value k does not exist in the given
        # matrix".
    print("No, the pair with the given product value k does not exist in the given matrix")

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 5 2 1
Enter {3} elements of row {2} separated by spaces = 4 6 3
Enter {3} elements of row {3} separated by spaces = 1 7 1
Enter some random number = 50
No, the pair with the given product value k does not exist in the given matrix

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 Check if a Pair with Given Product Exists in a Matrix Read More »

Program to Count Frequency of k in a Matrix of Size n Where Matrix(i, j) = i+j

Python Program to Count Frequency of k in a Matrix of Size n Where Matrix (i, j) = i+j

In the previous article, we have discussed Python Program to Calculate Sum of all Maximum Occurring Elements in Matrix

Given a number n (which is the size of the matrix)and another number k, the task is to find the frequency of k of the matrix with size n and matrix (i,j)=i+j.

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.

Examples:

Example1:

Input:

Given size of matrix = 3
Given k value = 6

Output:

The given k value{ 6 } frequency in the matix =  1

Example2:

Input:

Given size of matrix = 4
Given k value = 3

Output:

The given k value{ 3 } frequency in the matix =  2

Program to Count Frequency of k in a Matrix of Size n Where Matrix(i, j) = i+j in Python

Below are the ways to find the frequency of k of the matrix with size n and matrix (i,j)=i+j in python:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Import math module using the import keyword.
  • Give the number(size of matrix) as static input and store it in a variable.
  • Give another number k as static input and store it in another variable.
  • Create a function to say findfreqencyof_k() which takes the given number(size of matrix) and the given k value as the arguments and returns the frequency of k of the matrix with size n and matrix (i,j)=i+j.
  • Inside the function, check if the given number+1 is greater than or equal to the given k value using the if conditional statement.
  • If it is true, then return given k value -1.
  • Else return (2 * gvn_numb + 1 – gvn_k_val).
  • Pass the given number(size of matrix) and the given k value as the arguments to the findfreqencyof_k() function and store it in another variable.
  • Check if the above result is less than 0 using the if conditional statement.
  • If it is true, then print “The given element k does not exist in the matrix”.
  • Else print the frequency of the given k value.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math

# Create a function to say findfreqencyof_k() which takes the given number(size of matrix)
# and the given k value as the arguments and returns the frequency of k of the matrix
# with size n and matrix (i,j)=i+j.


def findfreqencyof_k(gvn_numb,  gvn_k_val):
    # Inside the function, check if the given number+1 is greater than or equal to the given
        # k value using the if conditional statement.
    if (gvn_numb + 1 >= gvn_k_val):
      # If it is true, then return given k value -1.
        return (gvn_k_val - 1)
    else:
      # Else return (2 * gvn_numb + 1 - gvn_k_val).
        return (2 * gvn_numb + 1 - gvn_k_val)


# Give the number(size of matrix) as static input and store it in a variable.
gvn_numb = 3
# Give another number k as static input and store it in another variable.
gvn_k_val = 6
# Pass the given number(size of matrix) and the given k value as the arguments to the
# findfreqencyof_k() function and store it in another variable.
rslt = findfreqencyof_k(gvn_numb, gvn_k_val)
# Check if the above result is less than 0 using the if conditional statement.
if (rslt < 0):
  # If it is true, then print "The given element k does not exist in the matrix".
    print("The given element{", gvn_k_val, "} does not exist in the matrix")
else:
  # Else print the frequency of the given k value.
    print(" The given k value{", gvn_k_val,
          "} frequency in the matix = ", rslt)

Output:

The given k value{ 6 } frequency in the matix =  1

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Import math module using the import keyword.
  • Give the number(size of matrix) as user input using the int(input()) function and store it in a variable.
  • Give another number k as user input using the int(input()) function and store it in another variable.
  • Create a function to say findfreqencyof_k() which takes the given number(size of matrix) and the given k value as the arguments and returns the frequency of k of the matrix with size n and matrix (i,j)=i+j.
  • Inside the function, check if the given number+1 is greater than or equal to the given k value using the if conditional statement.
  • If it is true, then return given k value -1.
  • Else return (2 * gvn_numb + 1 – gvn_k_val).
  • Pass the given number(size of matrix) and the given k value as the arguments to the findfreqencyof_k() function and store it in another variable.
  • Check if the above result is less than 0 using the if conditional statement.
  • If it is true, then print “The given element k does not exist in the matrix”.
  • Else print the frequency of the given k value.
  • The Exit of the Program.

Below is the implementation:

# Import math module using the import keyword.
import math

# Create a function to say findfreqencyof_k() which takes the given number(size of matrix)
# and the given k value as the arguments and returns the frequency of k of the matrix
# with size n and matrix (i,j)=i+j.


def findfreqencyof_k(gvn_numb,  gvn_k_val):
    # Inside the function, check if the given number+1 is greater than or equal to the given
        # k value using the if conditional statement.
    if (gvn_numb + 1 >= gvn_k_val):
      # If it is true, then return given k value -1.
        return (gvn_k_val - 1)
    else:
      # Else return (2 * gvn_numb + 1 - gvn_k_val).
        return (2 * gvn_numb + 1 - gvn_k_val)


# Give the number(size of matrix) as user input using the int(input()) function 
# and store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Give another number k as user input using the int(input()) function and
# store it in another variable.
gvn_k_val = int(input("Enter some random number = "))
# Pass the given number(size of matrix) and the given k value as the arguments to the
# findfreqencyof_k() function and store it in another variable.
rslt = findfreqencyof_k(gvn_numb, gvn_k_val)
# Check if the above result is less than 0 using the if conditional statement.
if (rslt < 0):
  # If it is true, then print "The given element k does not exist in the matrix".
    print("The given element{", gvn_k_val, "} does not exist in the matrix")
else:
  # Else print the frequency of the given k value.
    print(" The given k value{", gvn_k_val,
          "} frequency in the matix = ", rslt)

Output:

Enter some random number = 4
Enter some random number = 3
The given k value{ 3 } frequency in the matix = 2

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 Count Frequency of k in a Matrix of Size n Where Matrix (i, j) = i+j Read More »

Program to Interchange Elements of First and Last Rows in Matrix

Python Program to Interchange Elements of First and Last Rows in Matrix

In the previous article, we have discussed Python Program for Squares of Matrix Diagonal Elements

Given a matrix, the task is to interchange the elements of the first and the last rows of a given matrix.

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.

Examples:

Example1:

Input:

Given Matrix : 
2 3 4
1 7 45
8 2 3

Output:

The given matix after swapping the first and last row elements: 
8 2 3 
1 7 45 
2 3 4

Example2:

Input:

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

Output:

The given matix after swapping the first and last row elements: 
7 8 9 
4 5 6 
1 2 3

Program to Interchange Elements of First and Last Rows in Matrix in Python

Below are the ways to interchange the elements of the first and the last rows of a given matrix in python:

Method #1: Using For Loop (Static Input)

Approach:

  • 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.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, swap mtrx[0][itr], mtrx[mtrxrows-1][itr] using the comma(,) operator ( where itr is the iterator value and mtrxrows is the no of rows of matrix).
  • To print all the elements of the given matrix.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Print the element of the matrix by printing gvnmatrix[n][m] value where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 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])
print("The given matix after swapping the first and last row elements: ")
# Loop till the given number of rows using the For loop.
for itr in range(mtrxrows):
  # Inside the For loop, swap mtrx[0][itr], mtrx[mtrxrows-1][itr] using the comma(,) operator
  # ( where itr is the iterator value and mtrxrows is the no of rows of matrix).

    mtrx[0][itr], mtrx[mtrxrows-1][itr] = mtrx[mtrxrows-1][itr], mtrx[0][itr]

# 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 rows using another
    # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Print the element of the matrix by printing gvnmatrix[n][m] value
        # where n is the iterator value of the parent For loop and m is the iterator
        # value of the inner For loop.
        print(mtrx[n][m], end=' ')
    print()

Output:

The given matix after swapping the first and last row elements: 
7 8 9 
4 5 6 
1 2 3

Method #2: Using For loop (User Input)

Approach:

  • 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.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, swap mtrx[0][itr], mtrx[mtrxrows-1][itr] using the comma(,) operator ( where itr is the iterator value and mtrxrows is the no of rows of matrix).
  • To print all the elements of the given matrix.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Print the element of the matrix by printing gvnmatrix[n][m] value where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • The Exit of the Program.

Below is the implementation:

# 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)

print("The given matix after swapping the first and last row elements: ")
# Loop till the given number of rows using the For loop.
for itr in range(mtrxrows):
  # Inside the For loop, swap mtrx[0][itr], mtrx[mtrxrows-1][itr] using the comma(,) operator
  # ( where itr is the iterator value and mtrxrows is the no of rows of matrix).

    mtrx[0][itr], mtrx[mtrxrows-1][itr] = mtrx[mtrxrows-1][itr], mtrx[0][itr]

# 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 rows using another
    # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Print the element of the matrix by printing gvnmatrix[n][m] value
        # where n is the iterator value of the parent For loop and m is the iterator
        # value of the inner For loop.
        print(mtrx[n][m], end=' ')
    print()

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 2 3 4
Enter {3} elements of row {2} separated by spaces = 1 7 45
Enter {3} elements of row {3} separated by spaces = 8 2 3
The given matix after swapping the first and last row elements: 
8 2 3 
1 7 45 
2 3 4

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 Interchange Elements of First and Last Rows in Matrix Read More »

Program for Squares of Matrix Diagonal Elements

Python Program for Squares of Matrix Diagonal Elements

In the previous article, we have discussed Python Program to Swap Major and Minor Diagonals of a Square Matrix

Given a matrix and the task is to find the squares of all diagonal elements of a 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.

Diagonal Matrix:

The entries outside the main diagonal of a diagonal matrix are all 0; the word usually refers to square matrices.

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.

Examples:

Example1:

Input:

Given Matrix : 
1  5  4
2  3  6
4  2  1

Output:

The squares of diagonal elements of first diagonal:
1
9
1
The squares of diagonal elements of second diagonal:
16
9
16

Example2:

Input:

Given Matrix :
 3  8
 2  6

Output:

The squares of diagonal elements of first diagonal:
9
36
The squares of diagonal elements of second diagonal:
64
4

Program for Squares of Matrix Diagonal Elements in Python

Below are the ways to find the squares of all diagonal elements of a given matrix in python.

Method #1: Using For Loop (Static Input)

Approach:

  • 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.
  • 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 condition n is equal to m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then print the square of the gvnmatrix[n][m].
  • 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 condition n+m is equal to the mtrxrows-1 using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then print the square of the gvnmatrix[n][m].
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[1, 5, 4], [2, 3, 6], [4, 2, 1]]
# 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])
print("The squares of diagonal elements of first diagonal:")
# 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 condition n is equal to m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if (n == m):
          # If the statement is true, then print the square of the gvnmatrix[n][m]
            print(mtrx[n][m]**2)

# Loop till the given number of rows using the For loop.
print("The squares of diagonal elements of second diagonal:")
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 condition n+m is equal to the mtrxrows-1 using the if conditional
      # statement where n is the iterator value of the parent For loop and
      # m is the iterator value of the inner For loop.

        if (n+m == mtrxrows-1):
           # If the statement is true, then print the square of the gvnmatrix[n][m]
            print(mtrx[n][m]**2)

Output:

The squares of diagonal elements of first diagonal:
1
9
1
The squares of diagonal elements of second diagonal:
16
9
16

Method #2: Using For loop (User Input)

Approach:

  • 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.
  • 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 condition n is equal to m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then print the square of the gvnmatrix[n][m].
  • 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 condition n+m is equal to the mtrxrows-1 using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then print the square of the gvnmatrix[n][m].
  • The Exit of the Program.

Below is the implementation:

# 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)


print("The squares of diagonal elements of first diagonal:")
# 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 condition n is equal to m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if (n == m):
          # If the statement is true, then print the square of the gvnmatrix[n][m]
            print(mtrx[n][m]**2)

# Loop till the given number of rows using the For loop.
print("The squares of diagonal elements of second diagonal:")
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 condition n+m is equal to the mtrxrows-1 using the if conditional
      # statement where n is the iterator value of the parent For loop and
      # m is the iterator value of the inner For loop.

        if (n+m == mtrxrows-1):
           # If the statement is true, then print the square of the gvnmatrix[n][m]
            print(mtrx[n][m]**2)

Output:

Enter some random number of rows of the matrix = 2
Enter some random number of columns of the matrix = 2
Enter {2} elements of row {1} separated by spaces = 3 8
Enter {2} elements of row {2} separated by spaces = 2 6
The squares of diagonal elements of first diagonal:
9
36
The squares of diagonal elements of second diagonal:
64
4

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 for Squares of Matrix Diagonal Elements Read More »