How can I check if there are equal numbers in the same column or row in a numpy matrix?

Asked

Viewed 27 times

-4

from random import sample
import numpy as np

a = sample(range(1, 5), 4)
b = sample(range(1, 5), 4)
c = sample(range(1, 5), 4)
d = sample(range(1, 5), 4)

jogo = np.array([[a[0], a[1], b[1], b[2]],
                [a[2], a[3], b[2], b[3]],
                [c[0], c[1], d[0], d[1]],
                [c[2], c[3], d[2], d[3]]])

if there are equal numbers in the same row or column, I need to shuffle the samples to update the array until there are no equal values per row and column.

1 answer

0

You can use the pandas' nunique() method to return to you how many unique entries there are in each row or column. If you have four unique entries, it’s because the values are all different. Then use the all() numpy method to check that all rows/columns have 4 unique entries.

To check that all columns have only single entries:

import pandas as pd
valores_unicos = [pd.Series(jogo[:,coluna]).nunique() for coluna in range(4)]
todas_colunas_sem_repeticao = (np.array(valores_unicos) == 4).all()
todas_colunas_sem_repeticao

To check that all columns have only single entries:

import pandas as pd
valores_unicos = [pd.Series(jogo[:,linha]).nunique() for linha in range(4)]
todas_colunas_sem_repeticao = (np.array(valores_unicos) == 4).all()
todas_linhas_sem_repeticao

Both codes will return a boolean (True if all rows/columns have only unique values or False otherwise). If the result is False, draw again.

Browser other questions tagged

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