Generate random numbers in 2d numpy array without repeating Python

Asked

Viewed 639 times

3

Good afternoon, I’m trying to generate a 2d numpy array without repeating numbers. My code:

TAMANHO = 4
tabela= np.zeros((TAMANHO, TAMANHO), dtype = int)
tabela[:, 0] = np.random.randint(1, 170, TAMANHO)
tabela[:, 1] = np.random.randint(1, 170, TAMANHO)
tabela[:, 2] = np.random.randint(1, 170, TAMANHO)
tabela[:, 3] = np.random.randint(1, 170, TAMANHO)
tabela

For example instead of generating this 2D array set with repeated number:

array([[ 50,  39, 120, 129],
       [143, 147, 127,  82],
       [ 39,  63, 138,  48],
       [ 34,  63, 114, 119]])

I would like to generate randomly without repeating any number.

Somebody help me?

  • I knew how to do it: tabela = np.random.random_integers(170, size=(4,4)) but I am taking notice of depreciation in this function random_integers()

  • and if it is for values like 10 starting and 170 ending? put in appearance?

  • It is not good to go this way because the function has been depreciated and soon will stop working. I left the comment because I also want to know the answer.

  • OK, I’ll let you

2 answers

2

You can use numpy.random.Generator.choice:

from numpy.random import default_rng

rng = default_rng()
numbers = rng.choice(range(1, 171), size=(4, 4), replace=False)

I used range(1, 171) so that the numbers chosen are between 1 and 170 (in a range, the final value is not included, so I have to pass 171). And the argument replace=False indicates that there cannot be repeated values.


It is worth remembering that, for not having repetition of values, the range must have sufficient elements to fill all positions. For example, the case below gives error:

numbers = rng.choice(range(10), size=(4, 4), replace=False)

Like range(10) only has 10 possible values (the numbers between 0 and 9) and I want to generate an array 4 x 4 (ie with 16 values) without repetition, the code above gives an error:

Valueerror: Cannot take a Larger sample than Population when 'replace=False'

If I used replace=True, would not give error, but then the resulting array would have repeated numbers.

1

From what I understand, you want to implement an array in which all your values are missing repeated.

Note that when we are working with matrices we have to make clear the number of rows and columns.

Well, to solve this issue we can use the following code:

import numpy as np
from random import sample

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

# Montando uma matriz qualquer.
if v <= 170:
    numeros = sample(range(1, 171), v)
    print(np.array([numeros[i:i+n] for i in range(0, len(numeros), n)]))
else:
    print('Erro! Quantidade de sorteios maiores que o range!')

When we executed this code we received the first message: Digite o número de linhas: . At this point we must enter the number of lines of our matrix and press enter. Then we received the second message: Digite o número de colunas: . At this point we must enter the number of columns and press enter.

Note that the block if will control the amount of matrix elements. If this amount is equal to or equal to to the upper limit of the range, the array will be mounted and displayed. Otherwise, we will receive an error message that says: Erro! Quantidade de sorteios maiores que o range!. This error tells us that we want to generate an array with a larger amount of elements than the supported range.

If the entered values satisfy the arbitrary range, the code will assemble a list named after numbers, containing (m * n) drawn elements of range(1, 171).

Observation 1: I used the range(1, 171), because we know that the range in python always goes from 1 to n - 1. So, to draw values within the closed range [1,170], you must set the range to range(1, 171).

Observation 2: When I point out the number of lines - m - and the number of columns - n - the total number of values drawn will be (m * n).

After the draw the values will be organized and displayed

Let’s test the code?

Create a matrix that has 4 lines and 4 columns, in which each element is randomly drawn from the closed interval [1, 170].

To solve this example, we must execute the code, enter the value 4 - for the number of lines - and press enter, enter the value 4 - for the number of columns - and press enter.

From now on the code will assemble and display an order matrix 4 x 4 - with 16 values - with values drawn unrepeated.

Browser other questions tagged

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