Python. List generators for matrix operations. Examples

List generators for matrix operations. Examples


Contents


Search other resources:

1. Features of using list generators for matrices

List generators are useful for matrices (multidimensional arrays) of numbers of a given dimension. Matrices can be represented as tuples or lists. It is better to represent matrices as nested lists. In the most general case, the representation of a two-dimensional matrix in the form of a list in Python is as follows

MatrixName = [ [ a11, a12, ..., a1n ],
               [ a21, a22, ..., a2n ],
               ...
               [ am1, am2, ..., amn ] ]

here

  • MatrixName – matrix name;
  • a11, …, amn – matrix elements. These can be numbers, floating point numbers, characters, strings, logical values (true, false). They can also be more complex objects, for example, the same lists, tuples or sets.

It is list generators that are most convenient for processing matrices of any dimension, since they allow you to automatically scan rows and columns of matrices.

 

2. Examples of solving tasks using list generators
2.1. Matrix construction tasks
2.1.1. Construction of a matrix of a given dimension. Matrix elements are generated randomly

Task. Construct a matrix of a given dimension m×n and display it on the screen. Matrix elements are generated randomly and have a value from 1 to 10 inclusive.

Solution.

# List generators

# Task.
# Form a matrix of dimensions m*n, where m, n are entered from the keyboard.

# 1. Include the random module to generate random numbers
import random

# 2. Enter the dimension of the matrix
m = input('m = ')
n = input('n = ')

# 3. Form a matrix of size m*n.
# The values of the matrix elements are generated randomly
# within the limits [1, 10].
Matrix = [ [ random.randint(1, 11) for j in range(n)] for i in range(m) ]
print('Matrix:')

# 4. Display the result
for i in range(m):
    print(Matrix[i])

Test example

m = 4
n = 5
Matrix:
[10, 2, 3, 8, 7]
[6, 9, 2, 7, 11]
[2, 5, 9, 10, 4]
[10, 10, 11, 5, 10]

 

2.1.2. Formation of a two-dimensional matrix of a given dimension. Matrix elements are entered from the keyboard

Task.

Form an m×n matrix. The values of the sizes m, n and the values of the elements are entered from the keyboard.

Solution.

# List generators

# Task.
# Form a matrix of size m*n,
# where m, n are entered from the keyboard.

# 1. Enter the dimension of the matrix
m = input('m = ')
n = input('n = ')

# 2. Form a matrix of size m*n.
# The values of the matrix elements are entered from the keyboard.
Matrix = [ [ input("M["+str(i)+"]["+str(j)+"]=") for j in range(n) ]
            for i in range(m) ]

# 3. Display the result
print('Matrix:')
for i in range(m):
    print(Matrix[i])

Test example

m = 2
n = 3
M[0][0]=1
M[0][1]=2
M[0][2]=3
M[1][0]=4
M[1][1]=5
M[1][2]=6
Matrix:
[1, 2, 3]
[4, 5, 6]

 

2.2. Tasks for processing data that are placed in a matrix
2.2.1. Calculating the number of matrix elements that are greater than 5

Task. Construct an m×n matrix of integers, where m is the number of matrix rows, n is the number of matrix columns. The values m and n are entered from the keyboard. The numbers in the matrix are generated randomly and range from 1 to 10. Using the list generator, calculate the number of matrix elements that are more than 5.

Solution.

# List generators

# Task.
# Construct a matrix of integers of a given dimension m * n.
# Using a random number generator, calculate the number
# of matrix elements that are more than 5.

# 1. Include the random module
import random

# 2. Input the dimensions of the matrix
m = input("m = ") # rows
n = input("n = ") # columns

# 3. Forming an m*n matrix at random using a for loop
Matrix = []

# The outer loop of the matrix formation Matrix
for i in range(m):
    # Create a matrix row as a list
    row = []

    # Inner loop for generating row
    for j in range(n):
        # Form a random number from 1 to 10
        randNumber = random.randint(1, 11)

        # Add a random number to the list row
        row.append(randNumber)

    # Add row to Matrix
    Matrix.append(row)

# 4. Display the generated matrix Matrix for control
print('Matrix M:')
for i in range(m):
    print(Matrix[i])

# 5. Calculate the number of items greater than 5 using the list generator
count = len([ Matrix[i][j] for i in range(m) for j in range(n) if Matrix[i][j]>5 ])
print(count)

Test example

m = 3
n = 4
Matrix M:
[10, 4, 3, 4]
[3, 3, 10, 2]
[11, 9, 1, 4]
4

 

2.2.2. Task. Calculation of the sum of matrix elements according to the condition

Task. A two-dimensional array of integers of size m×n is given. Determine the sum of array elements that are within [5; 10]. Array elements are entered from the keyboard.

Solution.

When generating a list generator, the sum() function is used to calculate the sum.

# List generators

# Task.
# Calculate the sum of the matrix elements in the range [5; 10].
# The size of the matrix m, n and the values of the elements
# are entered from the keyboard.

# 1. Enter the dimension of the matrix
m = input('m = ')
n = input('n = ')

# 2. Form a matrix of size m * n.
# The values of the matrix elements are entered from the keyboard.
Matrix = [ [ input("M["+str(i)+"]["+str(j)+"]=") for j in range(n) ]
for i in range(m) ]

# 3. Calculate sum - use the list generator
summ = sum( Matrix[i][j] for i in range(m) for j in range(n)
            if (Matrix[i][j]>=5)and(Matrix[i][j]<=10))
print("summ = ", summ)

Test example

m = 2
n = 3
M[0][0]=3
M[0][1]=6
M[0][2]=2
M[1][0]=7
M[1][1]=1
M[1][2]=9
summ = 22

 

2.3. Tasks for creating new matrices based on the specified
2.3.1. Create third matrix C based on two matrices A, B

Task. Two matrices A, B of real numbers are given. The dimension of the matrices is m×n. Using the list generator, form the third matrix C, each element cij of which is determined by the rule

cij = aij + bij

Solution.

# List generators

# Task.
# Based on the matrices A, B, form the third matrix C.

# 1. Include the random module to generate random numbers
import random

# 2. Input the dimension of the matrices A, B
m = input('m = ')
n = input('n = ')

# 3. Generate m*n matrices A and B.
# The values of the matrix elements are generated randomly
# and are in the range [1; 100]
A = [ [random.randint(1, 101) for j in range(n)] for i in range(m) ]
B = [ [random.randint(1, 100) for j in range(n)] for i in range(m) ]

# 4. Generate third matrix C
C = [ [ A[i][j]+B[i][j] for j in range(n) ] for i in range(m) ]

# 5. Display matrix A for control
print('-------------------------')
print("A:")
for i in range(m):
    print(A[i])

# 6. Display matrix B for control
print('B:')
for i in range(m):
    print(B[i])

# 7. Display matrix C
print('C:')
for i in range(m):
    print(C[i])

Test example

m = 4
n = 6
-------------------------
A:
[91, 25, 72, 95, 53, 97]
[14, 53, 36, 66, 36, 48]
[78, 57, 69, 97, 51, 39]
[42, 47, 53, 47, 21, 34]
B:
[48, 73, 25, 13, 92, 22]
[45, 56, 95, 64, 43, 89]
[43, 44, 11, 29, 82, 32]
[95, 87, 33, 90, 67, 79]
C:
[139, 98, 97, 108, 145, 119]
[59, 109, 131, 130, 79, 137]
[121, 101, 80, 126, 133, 71]
[137, 134, 86, 137, 88, 113]

 

2.3.2. Create the resulting matrix based on the original one according to the specified condition

Task. A square matrix A of integers of dimension n is given. Based on the matrix A, form a matrix B, each element of which is determined by the rule:

B[i][j] = A[i][j] + 10

Use a list generator to get the resulting matrix B.

Solutions.

# List generators

# Task.
# Based on matrix A, create matrix B according to the rule:
# B[i][j] = A[i][j] + 10

# 1. Include the random module to generate random numbers
import random

# 2. Input the dimension of the matrix A
m = int(input('m = '))
n = int(input('n = '))

# 3. Form a matrix A of size m*n
# The values of the matrix elements are generated randomly and are in the range [-10; 10]
A = [ [random.randint(-10, 11) for j in range(n)] for i in range(m) ]

# 4. Display matrix A
print('-------------------------')
print("A:")
for i in range(m):
    print(A[i])

# 5. Forming matrix B using a list generator
B = [ [ A[i][j]+10 for j in range(n) ] for i in range(m) ]

# 6. Display the resulting matrix B
print("B:")
for i in range(m):
    print(B[i])

Test example

m = 3
n = 5
-------------------------
A:
[-4, 10, -5, 2, -6]
[10, -3, 5, 10, -7]
[7, -9, -3, -3, 11]
B:
[6, 20, 5, 12, 4]
[20, 7, 15, 20, 3]
[17, 1, 7, 7, 21]

 


Related topics