4x4 matrix with 20 elements

Asked

Viewed 457 times

0

Galera made a code in Python whose exercise asked to make a 4x4 matrix , show the amount of elements larger than 10 and show the final matrix. I did and everything was fine only that the matrix ta getting 20 elements and not separating by brackets every 4 elements. Here is my code

m = []
m1 = []
contadorp = 0
for i in range(4):
    m.append(int(input()))
    for j in range(4):
        m1.append(int(input()))
    if m[i] > 10 or m1[j] > 10 :
        contadorp = contadorp + 1
print('A quantidade de numeros maiores que 10 é ' , contadorp)
print(m,m1)


  • simple, the range starts at 0. soon: 0, 1, 2, 3, 4. Just you put 3, so it will have 4 houses from 0

4 answers

2


Well, you were doing some things wrong, look at my code I made based on your:

What you did wasn’t actually being a matrix, just the input of values and then the comparison.

Look what I’ve done:

I accumulate n elements in m1, which would be columns, and then deposit in m, which would become in a row, repeating this process depending on how many lines you want.

Then at the end I use another for to know which ones are bigger than 10. This could still be done in the other for, but how you didn’t use a variable in input() I didn’t change it.

m = []
m1 = []
contadorp = 0
for i in range(4): # Linhas
    for j in range(4): # Colunas
        m1.append(int(input('Numero:'))) # Eu adiciono os valores dentro de m1
    m.append(m1) # E depois, após adicionar 4 números, eu deposito em "m"
    m1 = [] # Zero m1 para poder depositar outro valor quando o For recomeçar

for i in m: # I vai representar cada lista dentro de m
    for j in i: # J vai representar cada valor dentro de I
        if j > 10:
            contadorp = contadorp + 1 # Faço a comparação
print('A quantidade de números maiores que 10 é ' , contadorp) # Dou o resultado
print(m)

exit:

>>> Numero:1
>>> Numero:2
>>> Numero:3
>>> Numero:4
>>> Numero:5
>>> Numero:6
>>> Numero:7
>>> Numero:8
>>> Numero:9
>>> Numero:10
>>> Numero:11
>>> Numero:12
>>> Numero:13
>>> Numero:14
>>> Numero:15
>>> Numero:16
>>> A quantidade de numeros maiores que 10 é  6
>>> [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

0

Another way (I don’t know if more elegant) to get what you want:

contador = 0
def foo(x):
  global contador
  if x > 10:
     contador += 1
  return x
matriz = [[ foo(int(input())) for i in range(4)] for i in range(4)]
print('A quantidade de numeros maiores que 10 é', contador)
print(matriz)

To define the matrix you can use list-comprehensions, and instead of setting a value for each element, I call a function passing as input parameter, and if the value is > 10 I increment +1 in the global counter variable

See working on repl it.

0

From what I understand, you want to assemble and display a square array of order 4, i.e., square matrix "4 x 4", in addition to showing the amount of elements that have values greater than 10.

Well, to solve this question we can use an algorithm that is able to assemble only square order matrices "4 x 4" or use an algorithm capable of mounting any order matrices "m x n" (m = rows and n = columns).

As my intention is to show, more comprehensively, the assembly of any matrix, then we can use the following algorithm below. Yeah, this will be able to assemble any order matrices "m x n".

As in your case the matrix will always be square, that is m = n, this implies that the number of rows is equal to the number of columns.

import numpy as np

m = int(input('Digite o número de linhas: '))
n = int(input('Digite o número de colunas: '))

cont = 0
matrizTemp = list()
for c in range(1, m + 1):
    linha = list()
    for i in range(1, n + 1):
        while True:
            try:
                valor = int(input(f'Digite o {i}º elemento de {c}ª linha: '))
                break
            except ValueError:
                print('\033[31mValor INVÁLIDO! Digite apenas inteiros!\033[m')
        if valor > 10:
            cont += 1
        linha.append(valor)
    matrizTemp.append(linha)

# Exibindo a matriz e suas dimensões.
matriz = np.array(matrizTemp)
print(f'\033[32mA matriz gerada é:\n{matriz}')
print(f'A quantidade de elementos maiores que 10 é: {cont}\033[m')

See here the functioning of the algorithm.

Note that when we run the algorithm we receive the following message; Digite o número de linhas. We must now enter the number of linhas that we want the matrix to have and press enter. Later we received the second message; Digite o número de colunas. We must now enter the number of colunas that we want the matrix to have and press enter.

After that we must insert each of the matrix elements. During the insertion of each matrix element a block if checks that each inserted value is greater than 10. If positive, the number of values greater than 10 in the counting variable cont.

At the end of the insertion of the values the algorithm will mount and display the matrix and also the amount of elements whose values are greater than 10.

Example

Imagine we want to create a matrix 4 x 4 which has the following values:

1, 2, 4, 6, 9, 10, 11, 3, 12, 16, 5, 7, 8, 14, 15, 20

When we execute this code we receive the message: digite o número de linhas:. Right now we must enter the number 4 and press enter. Then we received the second message: Digite o número de colunas:. At this point we must re-enter the number 4 and press enter. Then we received the following message: Digite o 1º elemento da 1ª linha:. At this point we must enter the first element, which in the case of the suggested example is 1. Later we are asked to enter the next value and, at this time, we must enter the next value.

After we have entered all the values suggested in the suggested example the script will assemble a square array of order 4 x 4 with all values typed and will also show the amount of terms that have values greater than 10.

Later the script will show the following outputs:

A matriz gerada é:
[[ 1  2  4  6]
 [ 9 10 11  3]
 [12 16  5  7]
 [ 8 14 15 20]]
A quantidade de elementos maiores que 10 é: 6

Note that the script will display the assembly of the order square matrix 4 x 4, in addition to displaying the amount of elements that have values bigger that 10

0

You can use nested list comprehension:

m = [[ input('Número') for i in range(4)] for x in range(4)]

Entry of data manually:

Número 1
Número 2
Número 3
Número 4
Número 5
Número 6
Número 7
Número 8
Número 9
Número 10
Número 11
Número 12
Número 13
Número 14
Número 15
Número 16

Showing the generated matrix:

print(m)
[['1', '2', '3', '4'], ['5', '6', '7', '8'], ['9', '10', '11', '12'], ['13', '14', '15', '16']]

Checking the numbers bigger than 10:

resultado = len([item for sublista in m for item in sublista if int(item) > 10])
print(f'Dentro da matriz existem {resultado} números maiores que 10')

Exit:

Dentro da matriz existem 6 números maiores que 10

Complete code:

m = [[ input('Número') for i in range(4)] for x in range(4)]
print(m)
resultado = len([item for sublista in m for item in sublista if int(item) > 10])
print(f'Dentro da matriz existem {resultado} números maiores que 10')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.