Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, generate pair of distinct random numbers

I want to use

np.random.randint(4, size=2)

to generate a pair of distinct random numbers from 0 to 3. The problem is that it sometimes gives (0,0), (3,3) etc. Is there a way to force the numbers to be distinct?

like image 497
Qubix Avatar asked Feb 04 '23 11:02

Qubix


2 Answers

you could use random.choice:

import numpy as np

np.random.choice(a=np.arange(4), size=2, replace=False)

or, more concise (as Nuageux pointed out):

np.random.choice(a=4, size=2, replace=False)
like image 109
hiro protagonist Avatar answered Feb 16 '23 04:02

hiro protagonist


for people who don't wanna use numpy

import random


left_end = 0
right_end = 3
length = 2
random.sample(range(left_end, right_end), k=length)

also you can wrap it in tuple if you need, since random.sample returns list object

like image 32
Azat Ibrakov Avatar answered Feb 16 '23 03:02

Azat Ibrakov