Author name: Vikram Chiluka

Program for Multiplication of Two Matrices in Python and C++ Programming

Python Program for Multiplication of Two Matrices | How do you do Matrix Multiplication in Python?

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Looking across the web for guidance on Multiplication of Two Matrices in Python? Before you begin your learning on Matrix Multiplication of Two Matrices know what is meant by a Matrix and what does Matrix Multiplication in actual means. This tutorial is going to be extremely helpful for you as it assists you completely on How to Multiply Two Matrices in Python using different methods like nested loops, nested list comprehension, etc. Furthermore, we have written simple python programs for multiplying two matrices clearly.

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.

What is Matrix Multiplication?

Matrix multiplication is only possible if the second matrix’s column equals the first matrix’s rows. A matrix can be represented in Python as a nested list ( a list inside a list ).

Examples for Matrix Multiplication:

Example 1:

Input:

Matrix 1  =  [  1  -8    7  ]
                    [  0   2    5  ]
                    [  1   6    2 ]
                      
Matrix 2 =   [   5    2   -6  ]
                    [   1    8    9 ]
                    [   3    5    7 ]

Output:

printing the matrix A :
1 -8 7
0 2 5
1 6 2
printing the matrix B :
5 2 -6
1 8 9
3 5 7
Printing the product of matrices : 
18 -27 -29
17 41 53
17 60 62

Example 2:

Input:

Matrix 1  =  1 2 3 
                  -5 8 7 
                   6 4 5 
                      
Matrix 2 =  2 7 9 
                  0 -8 5 
                  6 -5 2

Output:

Enter the number of rows and columns of the first matrix3
3
Enter the number of rows and columns of the second matrix3
3
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A21 = -5
Enter element A22 = 8
Enter element A23 = 7
Enter element A31 = 6
Enter element A32 = 4
Enter element A33 = 5

Enter elements of 2nd matrix: 
Enter element B11 = 2
Enter element B12 = 7
Enter element B13 = 9
Enter element B21 = 0
Enter element B22 = -8
Enter element B23 = 5
Enter element B31 = 6
Enter element B32 = -5
Enter element B33 = 2

printing the matrix A
1 2 3 
-5 8 7 
6 4 5

printing the matrix B
2 7 9 
0 -8 5 
6 -5 2 
Print the product of two matrices A and B
20 -24 25 
32 -134 9 
42 -15 84

Given two matrices, the task is to write a program in Python and C++ to multiply the two matrices.

Simple Python Program for Matrix Multiplication

Method #1: Using Nested Loops in Python

A matrix can be implemented as a nested list in Python (list inside a list).

Each element can be thought of as a row in the matrix.

X[0] can be used to choose the first row. Furthermore, the element in the first row, the first column can be chosen as X[0][0].

The multiplication of two matrices X and Y is defined if the number of columns in X equals the number of rows in Y.

Here we give the matrix input as static.

XY is defined and has the dimension n x l if X is a n x m matrix and Y is a m x l matrix (but YX is not defined). In Python, there are a few different approaches to implement matrix multiplication.

Below is the  implementation:

# given matrix A
A = [[1, - 8, 7],
     [0, 2, 5],
     [1, 6, 2]]
# given matrix B
B = [[5, 2, - 6],
     [1, 8, 9],
     [3, 5, 7]]
# Initialize the product of matrices elements to 0
matrixProduct = [[0, 0, 0],
                 [0, 0, 0],
                 [0, 0, 0]]
# Traverse the rows of A
for i in range(len(A)):
    #  Traverse the  columns of B
    for j in range(len(B[0])):
        # Traverse the  rows of B
        for k in range(len(B)):
            matrixProduct[i][j] += A[i][k] * B[k][j]
# printing the matrix A
print("printing the matrix A :")
for rows in A:
    print(*rows)
# printing the matrix B
print("printing the matrix B :")
for rows in B:
    print(*rows)
# printing the product of matrices
print("Printing the product of matrices : ")
for rows in matrixProduct:
    print(*rows)

Python Program for Matrix Multiplication using Nested Loops

Output:

printing the matrix A :
1 -8 7
0 2 5
1 6 2
printing the matrix B :
5 2 -6
1 8 9
3 5 7
Printing the product of matrices : 
18 -27 -29
17 41 53
17 60 62

Explanation:

To go through each row and column in our program, we used nested for loops. In the end, we add up the sum of the items.

This technique is simple, but it becomes computationally expensive as the order of the matrix increases.

We recommend NumPy for larger matrix operations because it is several (in the order of 1000) times faster than the above code.

Method #2: Matrix Multiplication List Comprehension Python

This program produces the same results as the previous one. To understand the preceding code, we must first know the built-in method zip() and how to unpack an argument list with the * operator.

To loop through each element in the matrix, we utilized nested list comprehension. At first glance, the code appears to be complicated and difficult to understand. However, once you’ve learned list comprehensions, you won’t want to go back to nested loops.

Below is the implementation:

# given matrix A
A = [[1, - 8, 7],
     [0, 2, 5],
     [1, 6, 2]]
# given matrix B
B = [[5, 2, - 6],
     [1, 8, 9],
     [3, 5, 7]]
# using list comprehension to do product of matrices
matrixProduct = [[sum(a*b for a, b in zip(row, col))
                  for col in zip(*B)] for row in A]

# printing the matrix A
print("printing the matrix A :")
for rows in A:
    print(*rows)
# printing the matrix B
print("printing the matrix B :")
for rows in B:
    print(*rows)
# printing the product of matrices
print("Printing the product of matrices : ")
for rows in matrixProduct:
    print(*rows)

Python Program for Matrix Multiplication using List Comprehension

Output:

printing the matrix A :
1 -8 7
0 2 5
1 6 2
printing the matrix B :
5 2 -6
1 8 9
3 5 7
Printing the product of matrices : 
18 -27 -29
17 41 53
17 60 62

Method #3: Using Nested Loops in C++

We used nesting loops in this program to iterate through and row and column. In order to multiply two matrices, we will do the multiplication of matrices as below

Let us take dynamic input in this case.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{
    int A[100][100], B[100][100], product[100][100], row1,
        col1, row2, col2, i, j, k;

    cout << "Enter the number of rows and columns of the "
            "first matrix";
    cin >> row1 >> col1;
    cout << "Enter the number of rows and columns of the "
            "second matrix";
    cin >> row2 >> col2;

    // Initializing matrix A with the user defined values
    for (i = 0; i < row1; ++i)
        for (j = 0; j < col1; ++j) {
            cout << "Enter element A" << i + 1 << j + 1
                 << " = ";
            cin >> A[i][j];
        }
    // Initializing matrix B with the user defined values
    cout << endl
         << "Enter elements of 2nd matrix: " << endl;
    for (i = 0; i < row2; ++i)
        for (j = 0; j < col2; ++j) {
            cout << "Enter element B" << i + 1 << j + 1
                 << " = ";
            cin >> B[i][j];
        }

    // Initializing the resultant product matrix with 0 to
    // all elements
    for (i = 0; i < row1; ++i)
        for (j = 0; j < col2; ++j) {
            product[i][j] = 0;
        }

    // Calculating the product of two matrices A and B
    for (i = 0; i < row1; ++i)
        for (j = 0; j < col2; ++j)
            for (k = 0; k < col1; ++k) {
                product[i][j] += A[i][k] * B[k][j];
            }
    // printing matrix A
    cout << endl << " printing the matrix A" << endl;
    for (i = 0; i < row1; ++i) {
        for (j = 0; j < col1; ++j) {
            cout << A[i][j] << "  ";
        }
        cout << endl;
    }
    // printing matrix B
    cout << endl << " printing the matrix B" << endl;
    for (i = 0; i < row2; ++i) {
        for (j = 0; j < col2; ++j) {
            cout << B[i][j] << "  ";
        }
        cout << endl;
    }

    // Print the product of two matrices A and B
    cout << "Print the product of two matrices A and B"
         << endl;
    for (i = 0; i < row1; ++i) {
        for (j = 0; j < col2; ++j) {
            cout << product[i][j] << "  ";
        }
        cout << endl;
    }

    return 0;
}

Output:

Enter the number of rows and columns of the first matrix3
3
Enter the number of rows and columns of the second matrix3
3
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A21 = -5
Enter element A22 = 8
Enter element A23 = 7
Enter element A31 = 6
Enter element A32 = 4
Enter element A33 = 5

Enter elements of 2nd matrix: 
Enter element B11 = 2
Enter element B12 = 7
Enter element B13 = 9
Enter element B21 = 0
Enter element B22 = -8
Enter element B23 = 5
Enter element B31 = 6
Enter element B32 = -5
Enter element B33 = 2

printing the matrix A
1 2 3 
-5 8 7 
6 4 5

printing the matrix B
2 7 9 
0 -8 5 
6 -5 2 
Print the product of two matrices A and B
20 -24 25 
32 -134 9 
42 -15 84

How to Multiply Two Matrices in Python using Numpy?

import numpy as np

C = np.array([[3, 6, 7], [5, -3, 0]])
D = np.array([[1, 1], [2, 1], [3, -3]])
E = C.dot(D)
print(E)

''' 

Output:

[[ 36 -12]
[ -1 2]]

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Related Programs:

Python Program for Multiplication of Two Matrices | How do you do Matrix Multiplication in Python? Read More »

Python Program to Generate Random Numbers except for a Particular Number in a List

Python Program to Generate Random Numbers except for a Particular Number in a List

In this article, we will learn how to create random numbers in Python except for a specific number. To achieve the required result, we will combine the random.choice() function with the list comprehension technique. See what we can come up with.
First, let’s look at how the random.choice() method works. This method selects a random number from a Python list or tuple and returns it.
To generate a random number from a given list that is not equal to a certain value, we first use the list comprehension method to get a list of elements that are not identical to the provided particular value that must be avoided while generating the random number from the list.

Then, as previously described, we can use the choice() method to retrieve any random value from the newly generated list.

Given a list, the task is to generate random numbers except for a particular number in a list in Python.

Examples:

Example1:

Input:

Given list = [12, 42, 48, 19, 24, 29, 23, 11, 19, 5, 7, 31, 39, 45, 47, 49]
Given element =19

Output:

The Random Element in the given list [12, 42, 48, 19, 24, 29, 23, 11, 19, 5, 7, 31, 39, 45, 47, 49] is [ 7 ]

Example2:

Input:

Given list = [1, 8, 19, 11, 647, 19, 98, 64, 57, 811, 83] 
Given element=8

Output:

The Random Element in the given list [1, 8, 19, 11, 647, 19, 98, 64, 57, 811, 83] is [ 19 ]

Python Program to Generate Random Numbers except for a particular number in a list

Below are the ways to generate random numbers except for a particular number in a list in Python.

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Method #1: Using List Comprehension (Static Input)

Approach:

  • Import the random module using the import statement.
  • Give the list as static input and store it in a variable.
  • Give the number as static input and store it in a variable.
  • Using List Comprehension create a new list that does not contain the given number.
  • Using the random. choice() function generates some random element in the given list.
  • Print the random element in the given list.
  • The Exit of the Program.

Below is the implementation:

# Import the random module using the import statement.
import random
# Give the list as static input and store it in a variable.
gvnlst = [12, 42, 48, 19, 24, 29, 23, 11, 19, 5, 7, 31, 39, 45, 47, 49]
# Give the number as static input and store it in a variable.
numbr = 24
# Using List Comprehension create a new list that does not contain the given number.
nwlist = [elmnt for elmnt in gvnlst if elmnt != numbr]
# Using the random. choice() function generates some random element in the given list.
rndm_numbrr = random.choice(nwlist)
# Print the random element in the given list.
print('The Random Element in the given list', gvnlst, 'is [', rndm_numbrr, ']'

Output:

The Random Element in the given list [12, 42, 48, 19, 24, 29, 23, 11, 19, 5, 7, 31, 39, 45, 47, 49] is [ 7 ]

Method #2: Using List Comprehension (User Input)

Approach:

  • Import the random module using the import statement.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the number as user input using int(input()) and store it in a variable.
  • Give the number as static input and store it in a variable.
  • Using List Comprehension create a new list that does not contain the given number.
  • Using the random. choice() function generates some random element in the given list.
  • Print the random element in the given list.
  • The Exit of the Program.

Below is the implementation:

# Import the random module using the import statement.
import random
# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the number as user input using int(input()) and store it in a variable.
numbr = int(input('Enter some random Number = '))
# Using List Comprehension create a new list that does not contain the given number.
nwlist = [elmnt for elmnt in gvnlst if elmnt != numbr]
# Using the random. choice() function generates some random element in the given list.
rndm_numbrr = random.choice(nwlist)
# Print the random element in the given list.
print('The Random Element in the given list', gvnlst, 'is [', rndm_numbrr, ']')

Output:

Enter some random List Elements separated by spaces = 1 8 19 11 647 19 98 64 57 811 83
Enter some random Number = 11
The Random Element in the given list [1, 8, 19, 11, 647, 19, 98, 64, 57, 811, 83] is [ 19 ]

Related Programs:

Python Program to Generate Random Numbers except for a Particular Number in a List Read More »

Program to Find a Number Repeating and Missing in an Array or List

Python Program to Find a Number Repeating and Missing in an Array or List

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

The task is to discover the missing and recurring numbers in the given n-dimensional array or list. The array’s values are in the inclusive range from 1 to n.

Examples:

Example1:

Input:

Given list = [2, 6, 4, 5, 4, 3]

Output:

The element which is repeating in the given list [2, 6, 4, 5, 4, 3] is [ 4 ]
The missing element in the given list [2, 6, 4, 5, 4, 3] is [ 1 ]

Example2:

Input:

Given list =[7, 1, 3, 7, 2, 5, 8, 6]

Output:

The element which is repeating in the given list [7, 1, 3, 7, 2, 5, 8, 6] is [ 7 ]
The missing element in the given list [7, 1, 3, 7, 2, 5, 8, 6] is [ 4 ]

Program to Find a Number Repeating and Missing in an Array or List in Python

Below are the ways to find a number repeating and missing in the given list.

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

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as static input and store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say freqncyValues)
  • Traverse in the freqncyValues using For loop.
  • Check if the value(frequency) is greater than 1 or not using the If statement.
  • If it is true then print it which is the only repeating element in the given list.
  • Calculate the sum of all keys in freqncyValues using the sum() and keys() function and store it in a variable sumele.
  • Calculate the total number of unique elements in the given list by calculating the length of the freqncyValues say unqelemts.
  • Increase the value of unqelemts by 1.
  • Apply the sum of n elements formula using  (n*(n+1))/2 where n is unqelemts.
  • Subtract the value of sumele from the above sum and store it in another variable.
  • This is the missing element in the given list and prints it.
  • 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 list as static input and store it in a variable.
gvnlst = [2, 6, 4, 5, 4, 3]
# Calculate the frequency of all the given list
# elements using the Counter() function which returns
# the element and its frequency as key-value pair and
# store this dictionary in a variable(say freqncyValues)
freqncyValues = Counter(gvnlst)
# Traverse in the freqncyValues using For loop.
for key in freqncyValues:
    # Check if the value(frequency) is greater
    # than 1 or not using the If statement.
    if(freqncyValues[key] > 1):
        # If it is true then print it which is the
        # only repeating element in the given list.
        print('The element which is repeating in the given list',
              gvnlst, 'is [', key, ']')
# Calculate the sum of all keys in freqncyValues 
# using the sum() and keys() function and store it in a variable sumele.
sumele = sum(freqncyValues.keys())
# Calculate the total number of unique elements
# in the given list by calculating the length of the freqncyValues say unqelemts.
unqelemts = len(freqncyValues)
# Increase the value of unqelemts by 1.
unqelemts = unqelemts+1
# Apply the sum of n elements formula using  (n*(n+1))/2 where n is unqelemts.
result = ((unqelemts*(unqelemts+1))//2)
# Subtract the value of sumele from the above sum and store it in another variable.
result = result-sumele
# This is the missing element in the given list and prints it.
print('The missing element in the given list', gvnlst, 'is [', result, ']')

Output:

The element which is repeating in the given list [2, 6, 4, 5, 4, 3] is [ 4 ]
The missing element in the given list [2, 6, 4, 5, 4, 3] is [ 1 ]

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

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say freqncyValues)
  • Traverse in the freqncyValues using For loop.
  • Check if the value(frequency) is greater than 1 or not using the If statement.
  • If it is true then print it which is the only repeating element in the given list.
  • Calculate the sum of all keys in freqncyValues using the sum() and keys() function and store it in a variable sumele.
  • Calculate the total number of unique elements in the given list by calculating the length of the freqncyValues say unqelemts.
  • Increase the value of unqelemts by 1.
  • Apply the sum of n elements formula using  (n*(n+1))/2 where n is unqelemts.
  • Subtract the value of sumele from the above sum and store it in another variable.
  • This is the missing element in the given list and prints it.
  • 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 list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Calculate the frequency of all the given list
# elements using the Counter() function which returns
# the element and its frequency as key-value pair and
# store this dictionary in a variable(say freqncyValues)
freqncyValues = Counter(gvnlst)
# Traverse in the freqncyValues using For loop.
for key in freqncyValues:
    # Check if the value(frequency) is greater
    # than 1 or not using the If statement.
    if(freqncyValues[key] > 1):
        # If it is true then print it which is the
        # only repeating element in the given list.
        print('The element which is repeating in the given list',
              gvnlst, 'is [', key, ']')
# Calculate the sum of all keys in freqncyValues 
# using the sum() and keys() function and store it in a variable sumele.
sumele = sum(freqncyValues.keys())
# Calculate the total number of unique elements
# in the given list by calculating the length of the freqncyValues say unqelemts.
unqelemts = len(freqncyValues)
# Increase the value of unqelemts by 1.
unqelemts = unqelemts+1
# Apply the sum of n elements formula using  (n*(n+1))/2 where n is unqelemts.
result = ((unqelemts*(unqelemts+1))//2)
# Subtract the value of sumele from the above sum and store it in another variable.
result = result-sumele
# This is the missing element in the given list and prints it.
print('The missing element in the given list', gvnlst, 'is [', result, ']')

Output:

Enter some random List Elements separated by spaces = 7 1 3 7 2 5 8 6
The element which is repeating in the given list [7, 1, 3, 7, 2, 5, 8, 6] is [ 7 ]
The missing element in the given list [7, 1, 3, 7, 2, 5, 8, 6] is [ 4 ]

Related Programs:

Python Program to Find a Number Repeating and Missing in an Array or List Read More »

Python Program to Find K’th SmallestLargest Element in Unsorted Array or List

Python Program to Find K’th Smallest/Largest Element in Unsorted Array or List

Given a list, the task is to find Kth’s Smallest and largest element in the given Unsorted list in Python.

Examples:

Example1:

Input:

Given List =[19, 24, 25, 36, 81, 144, 600, 900, 225, 4, 9, 1, 16, 49, 23, 49, 25, 10, 25]
Given k=6

Output:

The given list before sorting is [19, 24, 25, 36, 81, 144, 600, 900, 225, 4, 9, 1, 16, 49, 23, 49, 25, 10, 25]
The given list after sorting is [1, 4, 9, 10, 16, 19, 23, 24, 25, 25, 25, 36, 49, 49, 81, 144, 225, 600, 900]
The 6 th smallest element in the given list is [ 19 ]
The 6 th largest element in the given list is [ 49 ]

Example2:

Input:

Given list = [8, 45, 29, 19, 75, 68, 42, 13, 7, 9, 6, 4, 5, 96, 97, 91, 49, 72]
Given K =3

Output:

The given list before sorting is [8, 45, 29, 19, 75, 68, 42, 13, 7, 9, 6, 4, 5, 96, 97, 91, 49, 72]
The given list after sorting is [4, 5, 6, 7, 8, 9, 13, 19, 29, 42, 45, 49, 68, 72, 75, 91, 96, 97]
The 3 th smallest element in the given list is [ 6 ]
The 3 th largest element in the given list is [ 91 ]

Program to Find K’th Smallest/Largest Element in Unsorted Array or List in Python

Below are the ways to find Kth’s Smallest and largest element in the given Unsorted list in Python.

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Method #1: Using Sorting (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the value of K as static input and store it in a variable.
  • Sort the given list using the sort() function which sorts the given list in ascending order.
  • We can get the Kth smallest element in the given list by printing the k-1 index element in this sorted list.
  • We can get the Kth largest element in the given list by printing the -k index element in this sorted list( ‘-‘ refers to negative indexing).
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvnlst = [19, 24, 25, 36, 81, 144, 600, 900,
          225, 4, 9, 1, 16, 49, 23, 49, 25, 10, 25]
print('The given list before sorting is', gvnlst)
# Give the value of K as static input and store it in a variable.
kth = 6
# Sort the given list using the sort() function
# which sorts the given list in ascending order.
gvnlst.sort()
print('The given list after sorting is', gvnlst)
# We can get the Kth smallest element in the given list
# by printing the k-1 index element in this sorted list.
print('The', kth,
      'th smallest element in the given list is [', gvnlst[kth-1], ']')
# We can get the Kth largest element in the given list
# by printing the -k index element in this sorted list
# ( '-' refers to negative indexing).
print('The', kth,
      'th largest element in the given list is [', gvnlst[-kth], ']')

Output:

The given list before sorting is [19, 24, 25, 36, 81, 144, 600, 900, 225, 4, 9, 1, 16, 49, 23, 49, 25, 10, 25]
The given list after sorting is [1, 4, 9, 10, 16, 19, 23, 24, 25, 25, 25, 36, 49, 49, 81, 144, 225, 600, 900]
The 6 th smallest element in the given list is [ 19 ]
The 6 th largest element in the given list is [ 49 ]

Method #2: Using Sorting (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the value of K as user input and store it in a variable.
  • Sort the given list using the sort() function which sorts the given list in ascending order.
  • We can get the Kth smallest element in the given list by printing the k-1 index element in this sorted list.
  • We can get the Kth largest element in the given list by printing the -k index element in this sorted list( ‘-‘ refers to negative indexing).
  • The Exit of the program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Give the value of K as user input and store it in a variable.
kth = int(input('Enter some random Kth Number = '))

print('The given list before sorting is', gvnlst)
# Sort the given list using the sort() function
# which sorts the given list in ascending order.
gvnlst.sort()
print('The given list after sorting is', gvnlst)
# We can get the Kth smallest element in the given list
# by printing the k-1 index element in this sorted list.
print('The', kth,
      'th smallest element in the given list is [', gvnlst[kth-1], ']')
# We can get the Kth largest element in the given list
# by printing the -k index element in this sorted list
# ( '-' refers to negative indexing).
print('The', kth,
      'th largest element in the given list is [', gvnlst[-kth], ']')

Output:

Enter some random List Elements separated by spaces = 8 45 29 19 75 68 42 13 7 9 6 4 5 96 97 91 49 72
Enter some random Kth Number = 3
The given list before sorting is [8, 45, 29, 19, 75, 68, 42, 13, 7, 9, 6, 4, 5, 96, 97, 91, 49, 72]
The given list after sorting is [4, 5, 6, 7, 8, 9, 13, 19, 29, 42, 45, 49, 68, 72, 75, 91, 96, 97]
The 3 th smallest element in the given list is [ 6 ]
The 3 th largest element in the given list is [ 91 ]

Related Programs:

Python Program to Find K’th Smallest/Largest Element in Unsorted Array or List Read More »

Program to find Pair with the Greatest Product in an Array or List

Python Program to find Pair with the Greatest Product in an Array or List

Assume we are given an array with a number of elements our objective is to determine the highest value that is the product of two elements from the given array. If there is no such element, the output should be -1.

Given a list, the task is to find a pair with the greatest Product in the given array or list if the pair is not found then print -1.

Examples:

Example1:

Input:

Given list = [11, 2, 6, 12, 9, 99]

Output:

The Maximum product of pairs in the given list [11, 2, 6, 12, 9, 99] is [ 99 ]

Example2:

Input:

Given list = [11, 19, 24, 2, 48, 96]

Output:

Enter some random List Elements separated by spaces = 11 19 24 2 48 96
The Maximum product of pairs in the given list [11, 19, 24, 2, 48, 96] is [ 96 ]

Program to find Pair with the Greatest Product in an Array or List in Python

Below are the ways to find a pair with the greatest Product in the given array or list if the pair is not found then print -1.

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Take a variable maximproduct which stores the maximum product of pairs and initialize it to -1.
  • Calculate the length of the given list and store it in a variable lstlngth.
  • Iterate till the lstlngth using For loop use the iterator name as m.
  • Loop till lstlngth -1 using another For loop (Nested For loop) use the iterator name as n.
  • Loop from the second loop iterator value+1 to lstlngth using another For loop(Nested For loop) use the iterator name as p.
  • Check if givenlist[n]*givenlist[p] is equal to givenlist[m] using the If statement.
  • Using the max function calculate the maximum value of givenlist[m] and maximproduct and store it in maximproduct.
  • Print the maximproduct which is the result.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvnlst = [11, 2, 6, 12, 9, 99]
# Take a variable maximproduct which stores
# the maximum product of pairs and initialize it to -1.
maximproduct = -1
# Calculate the length of the given list and store it in a variable lstlngth.
lstlngth = len(gvnlst)
# Iterate till the lstlngth using For loop use the iterator name as m.

for m in range(lstlngth):
    # Loop till lstlngth -1 using another For loop
    # (Nested For loop) use the iterator name as n.
    for n in range(lstlngth - 1):
        # Loop from the second loop iterator value+1 to lstlngth using another For loop
        # (Nested For loop) use the iterator name as p.
        for p in range(n + 1, lstlngth):
            # Check if givenlist[n]*givenlist[p] is equal
            # to givenlist[m] using the If statement.
            if (gvnlst[n] * gvnlst[p] == gvnlst[m]):
                # Using the max function calculate the maximum value of
                # givenlist[m] and maximproduct and store it in maximproduct .
                maximproduct = max(maximproduct, gvnlst[m])
# Print the maximproduct which is the result.
print('The Maximum product of pairs in the given list',
      gvnlst, 'is [', maximproduct, ']')

Output:

The Maximum product of pairs in the given list [11, 2, 6, 12, 9, 99] is [ 99 ]

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Take a variable maximproduct which stores the maximum product of pairs and initialize it to -1.
  • Calculate the length of the given list and store it in a variable lstlngth.
  • Iterate till the lstlngth using For loop use the iterator name as m.
  • Loop till lstlngth -1 using another For loop (Nested For loop) use the iterator name as n.
  • Loop from the second loop iterator value+1 to lstlngth using another For loop(Nested For loop) use the iterator name as p.
  • Check if givenlist[n]*givenlist[p] is equal to givenlist[m] using the If statement.
  • Using the max function calculate the maximum value of givenlist[m] and maximproduct and store it in maximproduct.
  • Print the maximproduct which is the result.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Take a variable maximproduct which stores
# the maximum product of pairs and initialize it to -1.
maximproduct = -1
# Calculate the length of the given list and store it in a variable lstlngth.
lstlngth = len(gvnlst)
# Iterate till the lstlngth using For loop use the iterator name as m.

for m in range(lstlngth):
    # Loop till lstlngth -1 using another For loop
    # (Nested For loop) use the iterator name as n.
    for n in range(lstlngth - 1):
        # Loop from the second loop iterator value+1 to lstlngth using another For loop
        # (Nested For loop) use the iterator name as p.
        for p in range(n + 1, lstlngth):
            # Check if givenlist[n]*givenlist[p] is equal
            # to givenlist[m] using the If statement.
            if (gvnlst[n] * gvnlst[p] == gvnlst[m]):
                # Using the max function calculate the maximum value of
                # givenlist[m] and maximproduct and store it in maximproduct .
                maximproduct = max(maximproduct, gvnlst[m])
# Print the maximproduct which is the result.
print('The Maximum product of pairs in the given list',
      gvnlst, 'is [', maximproduct, ']')

Output:

Enter some random List Elements separated by spaces = 11 19 24 2 48 96
The Maximum product of pairs in the given list [11, 19, 24, 2, 48, 96] is [ 96 ]

Related Programs:

Python Program to find Pair with the Greatest Product in an Array or List Read More »

Python Program to Print all Perfect Squares from a List using List Comprehension and Math Module

Python Program to Print all Perfect Squares from a List using List Comprehension and Math Module

Given a list, the task is to write a program to print all perfect squares from the given list using list comprehension and Math Module.

Using list comprehension and the math module, you’ll learn how to check whether the elements in a Python list entered by the user are perfect squares or not.

List comprehensions are a neat trick that allows us to create a new list depending on the values of an existing list in only one line, making the code look shorter and more concise because we aren’t committing to the problem with an entire loop.
Python’s math module is a highly valuable tool because it offers a large number of mathematical functions that we may utilize in our programs.

Examples:

Example1:

Input:

Given list =[19, 24, 25, 36, 81, 144, 600, 900, 225, 4, 9, 1, 16, 49, 23, 49, 25, 10, 25]

Output:

The given list is = [19, 24, 25, 36, 81, 144, 600, 900, 225, 4, 9, 1, 16, 49, 23, 49, 25, 10, 25]
The perfect squares numbers of the given list is = [25, 36, 81, 144, 900, 225, 4, 9, 1, 16, 49, 49, 25, 25]

Example2:

Input:

Given list =[37, 82, 81, 467, 839, 8383, 1000, 1900, 10000, 9, 48, 49, 64, 121, 56]

Output:

Enter some random List Elements separated by spaces = 37 82 81 467 839 8383 1000 1900 10000 9 48 49 64 121 56
The given list is = [37, 82, 81, 467, 839, 8383, 1000, 1900, 10000, 9, 48, 49, 64, 121, 56]
The perfect squares numbers of the given list is = [81, 10000, 9, 49, 64, 121]

Python Program to Print all Perfect Squares from a List using List Comprehension and Math Module

Below are the ways to print all perfect squares from the given list using list comprehension and Math Module.

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

Method #1: Using List Comprehension and Math Modules (Static Input)

Approach:

Import the math module using the import statement.

Give the list as static input and store it in a variable.

Using List comprehension, floor(), and sqrt() functions to check whether the element value of the list is a perfect square or not. (An Element is said to be a perfect square if the floor value of the square root of the number is equal to the sqrt of the number)

Ex:

floor(sqrt(9))=3

sqrt(9)=3

Hence 9 is a perfect square.

Print the new list which contains only perfect squares of the original list.

The Exit of the program.

Below is the implementation:

# Import the math module using the import statement.
import math
# Give the list as static input and store it in a variable.
gvnlst = [19, 24, 25, 36, 81, 144, 600, 900,
          225, 4, 9, 1, 16, 49, 23, 49, 25, 10, 25]
print('The given list is =', gvnlst)
# Using List comprehension, floor(), and sqrt() functions
# to check whether the element value of the list is a perfect square or not.
# (An Element is said to be a perfect square if the floor value of the square root
# of the number is equal to the sqrt of the number)
prftsquareslist = [elemen for elemen in gvnlst if (
    math.sqrt(elemen) == math.floor(math.sqrt(elemen)))]
# Print the new list which contains only perfect squares of the original list.
print('The perfect squares numbers of the given list is =', prftsquareslist)

Output:

The given list is = [19, 24, 25, 36, 81, 144, 600, 900, 225, 4, 9, 1, 16, 49, 23, 49, 25, 10, 25]
The perfect squares numbers of the given list is = [25, 36, 81, 144, 900, 225, 4, 9, 1, 16, 49, 49, 25, 25]

Method #2: Using List Comprehension and Math Modules (User Input)

Approach:

Import the math module using the import statement.

Give the list as user input using list(),map(),input(),and split() functions.

Store it in a variable.

Using List comprehension, floor(), and sqrt() functions to check whether the element value of the list is a perfect square or not. (An Element is said to be a perfect square if the floor value of the square root of the number is equal to the sqrt of the number)

Ex:

floor(sqrt(9))=3

sqrt(9)=3

Hence 9 is a perfect square.

Print the new list which contains only perfect squares of the original list.

The Exit of the program.

Below is the implementation:

# Import the math module using the import statement.
import math
# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlst = list(
    map(int, input('Enter some random List Elements separated by spaces = ').split()))
print('The given list is =', gvnlst)
# Using List comprehension, floor(), and sqrt() functions
# to check whether the element value of the list is a perfect square or not.
# (An Element is said to be a perfect square if the floor value of the square root
# of the number is equal to the sqrt of the number)
prftsquareslist = [elemen for elemen in gvnlst if (
    math.sqrt(elemen) == math.floor(math.sqrt(elemen)))]
# Print the new list which contains only perfect squares of the original list.
print('The perfect squares numbers of the given list is =', prftsquareslist)

Output:

Enter some random List Elements separated by spaces = 37 82 81 467 839 8383 1000 1900 10000 9 48 49 64 121 56
The given list is = [37, 82, 81, 467, 839, 8383, 1000, 1900, 10000, 9, 48, 49, 64, 121, 56]
The perfect squares numbers of the given list is = [81, 10000, 9, 49, 64, 121]

Related Programs:

Python Program to Print all Perfect Squares from a List using List Comprehension and Math Module Read More »

Program to Find the Largest Number in a List

Python Program to Find the Largest Number in a List

Lists in Python:

Lists are one of Python’s most commonly used built-in data structures. You can make a list by putting all of the elements inside square brackets[ ] and separating them with commas. Lists can include any type of object, making them extremely useful and adaptable.

Given a list, the task is to find the largest number in the given list in Python.

Examples:

Example1:

Input:

given list =[1, 1, 2, 3, 4, 5, 7, 9, 15, 18, 18, 18, 26, 27, 34, 36, 47, 47, 52, 64, 65, 82, 82, 189, 274, 284, 467, 677,
                   871, 873, 876, 947, 1838, 2954, 5123]

Output:

The largest element present in the given list [1, 1, 2, 3, 4, 5, 7, 9, 15, 18, 18, 18, 26, 27, 34, 36, 47, 47, 52, 64, 65, 82,
82, 189, 274, 284, 467, 677, 871, 873, 876, 947, 1838, 2954, 5123] = 5123

Example2:

Input:

given list =[1, 2, 4, 8, 9, 11, 12, 13, 15, 15, 17, 18, 23, 23, 25, 28, 29, 31, 34]

Output:

The largest element present in the given list [1, 2, 4, 8, 9, 11, 12, 13, 15, 15, 17, 18, 23, 23, 25, 28, 29, 31, 34] = 34

Program to Find the Largest Number in a List in Python

There are several ways to find the largest element/item in the given list some of them are:

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Method #1:Using sort() function in Ascending Order(Static Input)

Approach:

  • Given the list as static input and store it in a variable.
  • Sort the given list using the sort() function(which sorts the elements in ascending order).
  • Calculate the length of the given list using the len() function and store it in a variable.
  • Print the largest element in the given list with the help of the length of the list variable(The last element can be found at the index length of list -1)
  • The Exit of the Program.

Below is the implementation:

# Given the list as static input and store it in a variable.
gvnList = [12, 34, 11, 9, 2, 4, 1, 23, 28,
           29, 25, 23, 31, 18, 15, 8, 13, 15, 17]
# Sort the given list using the sort() function
# (which sorts the elements in ascending order).
gvnList.sort()
# Calculate the length of the given list using the len() function
# and store it in a variable.
lstLeng = len(gvnList)
# Print the largest element in the given list with the help of the length of the
# list variable(The last element can be found at the index length of list -1)
largstele = gvnList[lstLeng-1]
print('The largest element present in the given list', gvnList, '=', largstele)

Output:

The largest element present in the given list [1, 2, 4, 8, 9, 11, 12, 13, 15, 15, 17, 18, 23, 23, 25, 28, 29, 31, 34] = 34

Method #2:Using sort() function in Ascending Order(User Input)

Approach:

  • Given the list as user input separated by spaces using map(),split(),list() and int functions.
  • Store the list in one variable.
  • Sort the given list using the sort() function(which sorts the elements in ascending order).
  • Calculate the length of the given list using the len() function and store it in a variable.
  • Print the largest element in the given list with the help of the length of the list variable(The last element can be found at the index length of list -1)
  • The Exit of the Program.

Below is the implementation:

# Given the list as user input separated by spaces
# using map(),split(),list() and int functions.
# Store the list in one variable.
gvnList = list(map(int, input('Enter some random elements to the list separated by spaces = ').split()))
# Sort the given list using the sort() function
# (which sorts the elements in ascending order).
gvnList.sort()
# Calculate the length of the given list using the len() function
# and store it in a variable.
lstLeng = len(gvnList)
# Print the largest element in the given list with the help of the length of the
# list variable(The last element can be found at the index length of list -1)
largstele = gvnList[lstLeng-1]
print('The largest element present in the given list', gvnList, '=', largstele)

Output:

Enter some random elements to the list separated by spaces = 36 18 1 34 9 7 64 15 284 1838 189 873 52 47 18 
65 677 876 2954 26 82 871 467 274 5123 82 947 27 47 18 1 4 3 5 2
The largest element present in the given list [1, 1, 2, 3, 4, 5, 7, 9, 15, 18, 18, 18, 26, 27, 34, 36, 47, 47, 52, 64, 65, 82,
82, 189, 274, 284, 467,  677, 871, 873, 876, 947, 1838, 2954, 5123] = 5123

Method #3:Using sort() function in Descending Order(User Input)

Approach:

  • Given the list as user input separated by spaces using map(),split(),list() and int functions.
  • Store the list in one variable.
  • Sort the given list in descending order using the sort() and reverse=True(which sorts the elements in descending order).
  • Print the largest element in the given list by printing the first element in the given list(which is having an index of 0)
  • The Exit of the Program.

Below is the implementation:

# Given the list as user input separated by spaces
# using map(),split(),list() and int functions.
# Store the list in one variable.
gvnList = list(map(int, input('Enter some random elements to the list separated by spaces = ').split()))
#Sort the given list in descending order using the sort() 
#and reverse=True(which sorts the elements in descending order).
gvnList.sort(reverse=True)

#Print the largest element in the given list by printing the first
#element in the given list(which is having an index of 0)
largstele = gvnList[0]
print('The largest element present in the given list', gvnList, '=', largstele)

Output:

Enter some random elements to the list separated by spaces = 36 282 194 196 578 1 2 34 727 84
The largest element present in the given list [727, 578, 282, 196, 194, 84, 36, 34, 2, 1] = 727

Method #4:Using max() function(Static Input)

This is the easiest and fastest approach.

Approach:

  • Given the list as static input and store it in a variable.
  • Print the maximum element in the given by providing the given list as an argument to max() function.
  • The Exit of the Program.

Below is the implementation:

# Given the list as static input and store it in a variable.
gvnList = [49, 189, 18, 9, 10, 2, 49, 1, 38, 29]
# Print the maximum element in the given by
# providing the given list as an argument to max() function.
largstele = max(gvnList)
print('The largest element present in the given list', gvnList, '=', largstele)

Output:

The largest element present in the given list [49, 189, 18, 9, 10, 2, 49, 1, 38, 29] = 189

This is the efficient way to find the largest element in the given list.

Method #5:Using max() function(User Input)

This is the easiest and fastest approach.

Approach:

  • Given the list as user input separated by spaces using map(),split(),list() and int functions.
  • Store the list in one variable.
  • Print the maximum element in the given by providing the given list as an argument to max() function.
  • The Exit of the Program.

Below is the implementation:

# Given the list as user input separated by spaces
# using map(),split(),list() and int functions.
# Store the list in one variable.
gvnList = list(map(int, input('Enter some random elements to the list separated by spaces = ').split()))
# Print the maximum element in the given by
# providing the given list as an argument to max() function.
largstele = max(gvnList)
print('The largest element present in the given list', gvnList, '=', largstele)

Output:

Enter some random elements to the list separated by spaces = 46 28 1 937 472 8545 28 1 83 94 28 95 27 58
The largest element present in the given list [46, 28, 1, 937, 472, 8545, 28, 1, 83, 94, 28, 95, 27, 58] = 8545

Related Programs:

Python Program to Find the Largest Number in a List Read More »

Program to Break a List into Chunks of Size N

Python Program to Break a List into Chunks of Size N

With the help of a few easy examples, we will learn how to break a list into chunks of any specified size N in Python.

A list is a collection of items like integers, floats, strings, and so on. Lists are mutable data structures, which means that their contents can be updated without changing their identity. Breaking huge lists into smaller parts is a common process used to improve the efficiency of a program.

Given a list and the number N the task is to break a list into parts of size N in Python.

Examples:

Example1:

Input:

Given List =['hello', 'this', 'is', 'btechgeeks', 'online', 'coding', 'platform']
Given Numb =2

Output:

[['hello', 'this'], ['is', 'btechgeeks'], ['online', 'coding'], ['platform']]

Example2:

Input:

Given list=good morning this is btechgeeks online programming platform for btech geeks
Given Number =3

Output:

[['good', 'morning', 'this'], ['is', 'btechgeeks', 'online'], ['programming', 'platform', 'for'], ['btech', 'geeks']]

Program to Break a List into Chunks of Size N in Python

Below are the ways to break a list into parts of size N in Python.

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

Method #1: Using yield keyword (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the Number N as static input and store it in another Variable.
  • Create a function listchunks() that accept the given list and the number as arguments and return the chunks of the given list.
  • Calculate the length of a list using the len() function.
  • Inside the function iterate from 0 to the length of the given list and give the third parameter as n in the range() function using the For loop.
  • Using the yield keyword slice from iterator value to the length of the list.
  • Pass the given list and number N to listchunks() function.
  • Convert this result to the list() and store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the Implementation:

# Create a function listchunks() that accept the given list
# and the number as arguments and return the chunks of the given list.
def listchunks(gvnlst, gvnumb):
        # Calculate the length of a list using the len() function.
    lstleng = len(gvnlst)
    # Inside the function iterate from 0 to the length of the
    # given list and give the third parameter as n in the range() function
    # using the For loop.
    for m in range(0, lstleng, gvnumb):
        # Using the yield keyword slice from iterator value to the length of the list.
        yield gvnlst[m:m + gvnumb]

# Give the list as static input and store it in a variable.
gvnlist = ['hello', 'this', 'is', 'btechgeeks', 'online', 'coding', 'platform']
# Give the Number N as static input and store it in another Variable.
numb = 2
# Pass the given list and number N to listchunks() function.
resllt = listchunks(gvnlist, numb)
# Convert this result to the list() and store it in a variable.
resllt = list(resllt)
# Print the above result.
print(resllt)

Output:

[['hello', 'this'], ['is', 'btechgeeks'], ['online', 'coding'], ['platform']]

So, the yield keyword’s most important distinguishing feature is its ability to return to the position it left at in the previous iteration of a loop. In the preceding example, after the list is separated into a sub-list of 2 objects, the yield keyword allows the function to return and resume from the third position.

Method #2: Using yield keyword (User Input)

Approach:

  • Give the list as user input using the list(), input() functions, and store the list in a variable.
  • Give the Number N as user input using the int(input()) function and store it in another Variable.
  • Create a function listchunks() that accept the given list and the number as arguments and return the chunks of the given list.
  • Calculate the length of a list using the len() function.
  • Inside the function iterate from 0 to the length of the given list and give the third parameter as n in the range() function using the For loop.
  • Using the yield keyword slice from iterator value to the length of the list.
  • Pass the given list and number N to listchunks() function.
  • Convert this result to the list() and store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the Implementation:

# Create a function listchunks() that accept the given list
# and the number as arguments and return the chunks of the given list.


def listchunks(gvnlst, gvnumb):
        # Calculate the length of a list using the len() function.
    lstleng = len(gvnlst)
    # Inside the function iterate from 0 to the length of the
    # given list and give the third parameter as n in the range() function
    # using the For loop.
    for m in range(0, lstleng, gvnumb):
        # Using the yield keyword slice from iterator value to the length of the list.
        yield gvnlst[m:m + gvnumb]


# Give the list as user input using the list(), input() functions,
# and store the list in a variable.
gvnlist = list(
    input('Enter some random string elements for the list = ').split())
# Give the Number N as user input using the int(input()) function
# and store it in another Variable.
numb = int(input('Enter some random number = '))
# Pass the given list and number N to listchunks() function.
resllt = listchunks(gvnlist, numb)
# Convert this result to the list() and store it in a variable.
resllt = list(resllt)
# Print the above result.
print(resllt)

Output:

Enter some random string elements for the list = good morning this is btechgeeks online programming platform for btech geeks
Enter some random number = 3
[['good', 'morning', 'this'], ['is', 'btechgeeks', 'online'], ['programming', 'platform', 'for'], ['btech', 'geeks']]

Related Programs:

Python Program to Break a List into Chunks of Size N Read More »

Program to Find Indices of the Non-Zero Elements in the Python list

Python Program to Find Indices of the Non-Zero Elements in the Python list

We’ll look at how to determine the indices of non-zero entries in a Python list. There may be times when we simply need to access the list’s non-zero elements. In such instances, we can apply the following techniques.

Lists:

A list is an ordered grouping of values. It can hold a variety of values. A list is a container that may be changed. This means that we can add new values, delete old ones, or change current ones.

A Python list is a mathematical concept that describes a finite sequence. Items or elements in a list are the values in a list. A list can have multiple instances of the same value. Each occurrence is treated as a separate item.

Given a list, the task is to find the indices of non-zero elements in the given list.

Examples:

Example1:

Input:

Given list = [11, 19, 0, 8, 45, 0, 29, 0, 19, 0, 26, 0, 33]

Output:

The non zero elements indices in the given list are =  [0, 1, 3, 4, 6, 8, 10, 12]

Example2:

Input:

Given list = 25 0 7 0 0 0 9 5

Output:

The non zero elements indices in the given list are = [0, 2, 6, 7]

Program to Find Indices of the Non-Zero Elements in the Python list in Python

Below are the ways to find the indices of non-zero elements in the given list.

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Take an empty list and initialize it’s with an empty list using list() and [].
  • Calculate the length of the given list using the len() function.
  • Loop till the length of the given list using the For loop.
  • Check if the element in the given list is equal to 0 or not using the If conditional statement.
  • If it is a non-zero element then append the index to the new list using the append() function.
  • Print the index list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvnlst = [11, 19, 0, 8, 45, 0, 29, 0, 19, 0, 26, 0, 33]
# Take an empty list and initialize it’s with an empty list using list() and [].
nwlist = []
# Calculate the length of the given list using the len() function.
gvnlstlen = len(gvnlst)
# Loop till the length of the given list using the For loop.
for m in range(gvnlstlen):
    # Check if the element in the given list is equal to 0 or not
    # using the If conditional statement.
    if(gvnlst[m] != 0):
        # If it is non-zero element then append the index to the new list
        # using the append() function.
        nwlist.append(m)
# Print the index list.
print('The non zero elements indices in the given list are = ', nwlist)

Output:

The non zero elements indices in the given list are =  [0, 1, 3, 4, 6, 8, 10, 12]

Method #2: Using For Loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Take an empty list and initialize it’s with an empty list using list() and [].
  • Calculate the length of the given list using the len() function.
  • Loop till the length of the given list using the For loop.
  • Check if the element in the given list is equal to 0 or not using the If conditional statement.
  • If it is a non-zero element then append the index to the new list using the append() function.
  • Print the index list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Take an empty list and initialize it’s with an empty list using list() and [].
nwlist = []
# Calculate the length of the given list using the len() function.
gvnlstlen = len(gvnlst)
# Loop till the length of the given list using the For loop.
for m in range(gvnlstlen):
    # Check if the element in the given list is equal to 0 or not
    # using the If conditional statement.
    if(gvnlst[m] != 0):
        # If it is non-zero element then append the index to the new list
        # using the append() function.
        nwlist.append(m)
# Print the index list.
print('The non zero elements indices in the given list are = ', nwlist)

Output:

Enter some random List Elements separated by spaces = 25 0 7 0 0 0 9 5
The non zero elements indices in the given list are = [0, 2, 6, 7]

Method #3: Using List Comprehension (Static Input)

The method used in the sample program is another way to find the indices of non-zero elements. This is a concise summary implementation of the preceding algorithm. To transform the list into an iterable, we use the enumerate() method in this method.

Approach:

  • Give the list as static input and store it in a variable.
  • Use the list comprehension and enumerate to find all non-zero elements indices in the given list.
  • Print this indices list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvnlst = [11, 19, 0, 8, 45, 0, 29, 0, 19, 0, 26, 0, 33]
# Use the list comprehension and enumerate to find all non-zero elements
# indices in the given list.
nwlist = [index for index, listelement in enumerate(
    gvnlst) if listelement != 0]
# Print the index list.
print('The non zero elements indices in the given list are = ', nwlist)

Output:

The non zero elements indices in the given list are =  [0, 1, 3, 4, 6, 8, 10, 12]

Method #4: Using List Comprehension (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Use the list comprehension and enumerate to find all non-zero elements indices in the given list.
  • Print this indices list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlst = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
# Use the list comprehension and enumerate to find all non-zero elements
# indices in the given list.
nwlist = [index for index, listelement in enumerate(
    gvnlst) if listelement != 0]
# Print the index list.
print('The non zero elements indices in the given list are = ', nwlist)

Output:

Enter some random List Elements separated by spaces = 7 9 0 0 6 3 0 0
The non zero elements indices in the given list are = [0, 1, 4, 5]

Related Programs:

Python Program to Find Indices of the Non-Zero Elements in the Python list Read More »

Write a Program for Matrix Subtraction

Program to Subtract two Matrices in Python & C++ Programming

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 as 5*4 matrix.

What is matrix subtraction:

Given two matrices of same order(dimensions) then we can easily add the two matrices by doing the difference of corresponding elements in both the matrices.

Example:

 

Here Matrix C is matrix subtraction  of the matrices A and B.

Examples for matrix addition:

Input:

Matrix 1  =    2    3   1
                      1    2   3
                     -3   0   2    
Matrix 2 =      1    4    2
                     -4    5   -1
                      2    1     4

Output:

Printing the difference of matrices : 
1 -1 -1
5 -3 4
-5 -1 -2

Explanation:

 Here we subtracted the corresponding elements in both matrices

Program for Matrix Subtraction

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using nested Loops in Python

A matrix can be implemented as a nested list in Python (list inside a list). Each variable can be thought of as a row in the matrix.

Approach:

  • Create two two-dimensional arrays, a and b, and set their values. (In this case, we used a  initialised statically)
  • Calculate the number of rows and columns in the array a (since the dimensions of both arrays are the same) and store it in the variables rows and columns.
    Declare a new array diff, this time with dimensions in rows and columns.
  • Calculate the difference between the respective elements by looping around the arrays a and b.
  • Print the difference of two matrices.

Below is the  implementation:

# given matrix A
A = [[2, 3, 1],
     [1, 2, 3],
     [-3, 0, 2]]
# given matrix B
B = [[1, 4, 2],
     [-4, 5, -1],
     [2, 1, 4]]
# Initialize the difference of matrices elements to 0
matrixDiff = [[0, 0, 0],
              [0, 0, 0],
              [0, 0, 0]]
# Traverse the rows
for rows in range(len(A)):
    # Traverse the  columns
    for columns in range(len(A[0])):
        matrixDiff[rows][columns] = A[rows][columns] - B[rows][columns]
# printing the difference of matrices
print("Printing the difference of matrices : ")
for rows in matrixDiff:
    print(*rows)

Output:

Printing the difference of matrices : 
1 -1 -1
5 -3 4
-5 -1 -2

Method #2:Using List Comprehension in Python

The program’s output is the same as previously. For iterating through each element in the array, we used the nested list comprehension.

Understanding the list helps us to write concise codes and we need to always try to use them in Python. They’re really beneficial.

Below is the implementation:

# given matrix A
A = [[2, 3, 1],
     [1, 2, 3],
     [-3, 0, 2]]
# given matrix B
B = [[1, 4, 2],
     [-4, 5, -1],
     [2, 1, 4]]
# Initialize the difference of matrices elements to 0
matrixDiff = [[0, 0, 0],
              [0, 0, 0],
              [0, 0, 0]]

# using list comprehension
matrixDiff = [[A[i][j] - B[i][j]
               for j in range(len(A[0]))] for i in range(len(A))]

# printing the difference of matrices
print("Printing the difference of matrices : ")
for rows in matrixDiff:
    print(*rows)

Output:

Printing the sum of matrices : 
16 -1 -5
6 11 6

Method #3:Using nested loops in C++

We used nesting loops in this program to iterate through and row and column. In the two matrices we will subract the appropriate elements and store them in the result at each level.

Let us take dynamic input in this case.

Below is the implementation:

#include <iostream>
using namespace std;
int main()
{
    int rows, columns, A[100][100], B[100][100], DiffMatrix[100][100], i, j;
    cout << "Enter the number of rows of the matrix "<<endl;
    cin >> rows;
    cout << "Enter the number of columns of the matrix"<<endl;
    cin >> columns;
    cout << "Enter the elements of first matrix " << endl;
    // Initializing matrix A with the user defined values
    for(i = 0; i < rows; ++i)
       for(j = 0; j < columns; ++j)
       {
           cout << "Enter element A" << i + 1 << j + 1 << " = ";
           cin >> A[i][j];
       }
   // Initializing matrix B with the user defined values
    cout << endl << "Enter elements of 2nd matrix: " << endl;
    for(i = 0; i < rows; ++i)
       for(j = 0; j < columns; ++j)
       {
           cout << "Enter element B" << i + 1 << j + 1 << " = ";
           cin >> B[i][j];
       }
    // Performing matrix addition by doing diffeerence of given two matrices A and B
    for(i = 0; i < rows; ++i)
        for(j = 0; j < columns; ++j)
            DiffMatrix[i][j] = A[i][j] - B[i][j];
    //printing matrix A
    cout << endl << " printing the matrix A" << endl;
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << A[i][j] << "  ";
    }
    cout << endl;
}
    //printing matrix B
    cout << endl << " printing the matrix B" << endl;
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << B[i][j] << "  ";
    }
    cout << endl;
}
    //printing the difference of matrices
    cout << endl << " printing the difference of matrices A and B" << endl;
    
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << DiffMatrix[i][j] << "  ";
    }
    cout << endl;
}
    return 0;
}

Output:

Enter the number of rows of the matrix 
4
Enter the number of columns of the matrix
4
Enter the elements of first matrix 
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A14 = 4
Enter element A21 = 5
Enter element A22 = 6
Enter element A23 = 5
Enter element A24 = 2
Enter element A31 = -5
Enter element A32 = 9
Enter element A33 = 1
Enter element A34 = 5
Enter element A41 = 0
Enter element A42 = 5
Enter element A43 = 2
Enter element A44 = 5

Enter elements of 2nd matrix: 
Enter element B11 = 1
Enter element B12 = 9
Enter element B13 = 5
Enter element B14 = 3
Enter element B21 = 8
Enter element B22 = -4
Enter element B23 = -8
Enter element B24 = 0
Enter element B31 = 5
Enter element B32 = 1
Enter element B33 = 7
Enter element B34 = -3
Enter element B41 = -8
Enter element B42 = 1
Enter element B43 = 2
Enter element B44 = 0

printing the matrix A
1 2 3 4 
5 6 5 2 
-5 9 1 54 
0 5 2 5

printing the matrix B
1 9 5 3 
8 -4 -38 0 
5 1 7 -3 
-8 1 2 0

printing the difference of matrices A and B
0 -7 -2 1 
-3 10 43 2 
-10 8 -6 57 
8 4 0 5

Related Programs:

Program to Subtract two Matrices in Python & C++ Programming Read More »