Print null or non-null in Python array

Asked

Viewed 295 times

2

If matrix has only zero print 'null' if not print 'not null' I did so:

m=[[0,0,0],[0,0,0],[0,0,0]]
soma1=0
for novo1 in m[0]:
    soma1+=novo1
soma2=0
for novo2 in m[1]:
    soma2+=novo2
soma3=0
for novo3 in m[2]:
    soma3+=novo3

if soma1==0 and soma2==0 and soma3==0:
    print('nulo')
else:
    print('nao nulo')

But this way I have to do it manually.

I would like to know how I do without being like this, but considering for example a larger matrix. Like if it was a 500-number matrix, I couldn’t do it like this.

  • Why are you adding the values to "0"?

  • I don’t understand the sorry question about the list? if it is is I was testing here but can consider another list for example [[0,0,1],[0,0,0],[0,0,0]] in the output will say that it is not null

  • 3

    Should it return "null" if the matrix has all elements equal to zero or if the sum of all elements is 0? Basically, [0, -1, 1] does not have all values equal to zero, but the sum will be 0, in this case what should be the output?

4 answers

3


Resolution

Using two for, one to go through "m" and one to go through your sub-items, I created another array for the items that will be summed, but if you are going to use only sums with zero it is better to exchange the array and put the static value, and finally I created a flag called "isNulo" so if there is any value that is not zero it is set to "False".

Case 1

m=[[0,0,0],[0,0,0],[0,0,0]]
soma=[0,0,0]
isNulo=True
count=0

for x in m:
  for y in x:
    soma[count]+=y
    if soma[count] != 0:
      isNulo = False
  count += 1
    
if isNulo:
    print('nulo')
else:
    print('nao nulo')

Execute

Case 2

If that’s what the Anderson quoted, "sum of all elements is 0", just put the for outside the for intern

m=[[0,0,0],[0,0,0],[0,0,0]]
soma=[0,0,0]
isNulo=True
count=0

for x in m:
  for y in x:
    soma[count]+=y
  if soma[count] != 0:
    isNulo = False
  count += 1
    
if isNulo:
    print('nulo')
else:
    print('nao nulo')

Execute

Case 3

The same idea of case 2, but without the need for the sum with values other than zero

m=[[0,1,-1],[0,0,0],[0,0,0]]
isNulo=True
count=0

for x in m:
  soma = 0
  for y in x:
    soma+=y
  if soma != 0:
    isNulo = False

if isNulo:
    print('nulo')
else:
    print('nao nulo')

Execute

  • 1

    thank you very much!

  • 1

    And what would happen if the "matrix" had more than 2 sizes?

3

No need to keep adding up the elements, just go through the lists and check if each value is different from zero.

One way to solve is to first create a function that checks if a list has only zeros:

def somente_zeros(lista):
    for elemento in lista:
        if elemento != 0:
            return False;
    return True;

Note that if you find an element that is not zero, the function already returns False (not only zeros), because in this case I don’t even need to go through the rest of the list.

If the for finish, it means that no one entered the if, and therefore all elements are equal to zero, and the function returns True.

Now just go through the matrix. At the bottom, the matrix is just a list of lists: a list in which each element is also a list. So just make a for in the matrix elements, and use the function above to check that it only has zeros:

m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

# para cada linha da matriz
for linha in m:
    # se encontrou algum elemento diferente de zero, já imprime a mensagem e sai do loop
    if not somente_zeros(linha):
        print('nao nulo')
        break
else:
    print('nulo')

The for traverse each row of the matrix and pass it to the function somente_zeros. If the list has an element other than zero, enter the if, which already prints the "not null" message and exits the loop (the break interrupts the for).

If none of the lines enter the if (that is, all elements are equal to zero), the break is not called and the block else is executed (yes, in Python, a for may have a block else associated).


As a general solution for "matrices" with more than two dimensions (i.e., list lists of lists of lists...) you can create another auxiliary function to convert the matrix to a list of one dimension:

from collections.abc import Iterable

def flatten(matriz):
    result = []
    for elemento in matriz:
        # se for um elemento iterável (exceto strings), faz o flatten recursivamente
        if isinstance(elemento, Iterable) and not isinstance(elemento, str):
            result.extend(flatten(elemento))
        else:
            result.append(elemento)
    return result

With this, no matter the dimension of the matrix, it will be reduced to a single list, containing all the elements. Therefore, you just need to scroll through it and check if some element is not zero:

m = [
    [
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
    ],
    [
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
    ],
    [
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
        [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
    ]
]

for elemento in flatten(m):
    if elemento != 0:
        print('nao nulo')
        break
else:
    print('nulo')

The idea is the same as the function somente_zeros: if you find an element that is not zero, print "not null" and stop the loop (do not need to check the rest as I have already found an element that is not zero).

If the for comes to an end, it means that all elements are zero. The block else is executed and prints "null".

  • 1

    @ hkotsubo, Cool! (+1)

1

Like True > False we can simply calculate the minimum recursively:

def all_0(x):
  if type(x) is list: return min([all_0(y) for y in x])
  else              : return x == 0

applicable to "matrices" of any size, homogeneous or heterogeneous (generalized lists)

print(all_0([[0,[0,0,0],1,0],[0,0,0],[0,0,0]]))           ## False

print(all_0([[0,[0,0,0],0,0],[0,0,0],[0,[[0,0,],0],0]]))  ## True

1

Use Numpy

You are constructing what you call the matrix through the lists of python, I have my doubts if Voce can call this matrix in the mathematical sense of the word. Using the numpy Voce you can build matrices through genuine arrays and do various specific operations for matrices. Solving your question:

import numpy as np
m1 = np.array([np.zeros(100),np.zeros(100)])
m2 = m1.copy()
m2[0][10]=1

# Testando m1
print("Nulo") if m1.sum()==0 else print("Não Nulo")
Nulo

# Testando m2
print("Nulo") if m2.sum()==0 else print("Não Nulo")
Não Nulo

Edited

With numpy you can also count the zeros in a matrix with only one command, so we could do so too:

m1 = np.array([[0,0,0],[0,0,0],[0,0,0]])
print('Nulo') if not np.count_nonzero(m1) else print('Não Nulo')
Nulo

m2 = m1.copy()
m2[0,0]=1
print('Nulo') if not np.count_nonzero(m2) else print('Não Nulo')
Não Nulo

Browser other questions tagged

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