Matrix 4x4 is getting 20 elements

2

Galera made a code in Python whose exercise asked to make a 4x4 matrix, show the number of elements greater than 10 and show the final matrix. I did and it was all right only that the array is getting 20 elements and is not separated 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)


    
asked by anonymous 23.05.2017 / 19:46

2 answers

2

Well, you were doing some things wrong, see my code I made based on yours:

What you did was not really an array, just input values and then comparison.

Here's what I did:

I build 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 rows you want.

Then to the end I use another for to know which ones are greater than 10. This could be done in the other for , but since you did not use a variable in input() I did not 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)

Output:

>>> 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]]
    
23.05.2017 / 20:13
0

Another way (if not 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 array you can use list-comprehensions , and instead of defining a value for each element, I call a function passing as input the parameter, and if the value is > 10 I increment +1 in the global counter variable

See working at repl.it

    
23.05.2017 / 20:44