samedi 13 novembre 2021

How to generate a numpy array with random values that are all different from each other

I've just started to learn about Python libraries and today I got stuck at a numpy exercise.

Let's say I want to generate a 5x5 random array whose values are all different from each other. Further, its values have to range from 0 to 100.

I have already look this up here but found no suitable solution to my problem. Please see the posts I consulted before turning to you:

Numpy: Get random set of rows from 2D array Numpy Random 2D Array

Here, my attempt at this:

import numpy as np

M = np.random.randint(1, 101, size=25)

for x in M:
    for y in M:
        if x in M == y in M:
            M = np.random.randint(1, 101, size=25)
            print(M)

By doing this, all I get is a value error: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Thus, my second attempt has been the following:

M = np.random.randint(1, 101, size=25)
a = M[x]
b = M[y]

for a.any in M:
    for b.any in M:
        if a.any in M == b.any in M:
            M = np.random.randint(1, 101, size=25)
            print(M)

Once again, I got an error: AttributeError: 'numpy.int64' object attribute 'any' is read-only.

Could you please let me know what am I doing wrong? I've spent days going over this but nothing else comes to mind :(

Thank you so much!




Aucun commentaire:

Enregistrer un commentaire