Random number without repetitions

Hi all,

How can I make sure that a random number generated using randint() does not occur on multiple trials?

Thanks!

Hello bear

one way would be to generate the random numbers in advance, so at the begin of the experiment instead of on each trial.

Best wishes Jens

Hi Jens,

The random numbers appear in an odd/even basline task and will range from 1 to 9. They will appear every 60-90 s for 6-8 s each. So the same numbers could appear in different trial periods, but within the same period should not repeat. Does this make sense?

Thanks :slight_smile:

The way I create a random digit (0-9) that isn’t the same as the previous digit is (I think) in my digit span demo.

thisNumber = (thisNumber + randint(1,10))%10

Hello bear,

you could follow @wakecarter’s suggestion or create an array containing the number you want to present and shuffle that array, show a number, delete it from the array and repeat these steps.

Best wishes Jens

Sorry - I missed that you probably want no repeats, rather than just no consecutive repeats. I’d use @JensBoelte suggestion and reset the list every trial period.

allNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
shuffle(allNumbers)

then

thisNumber = allNumbers.pop()

In Begin Routine of the odd/even task, I now put the following code, as you suggested:

allNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
shuffle(allNumbers)
randNumber = allNumbers.pop()

However, in a practice trial, I still got the number 3 twice in a row. I guess I did it wrong… do the first two lines of your code @wakecarter go in a different tab?

Hello bear,

the first two lines have to be “outside” of the practice-trials loop. Otherwise you are executing the first two lines repeatedly. Or you need an index and an if-construction to execute the first two lines only once.

if trials.thisN == 0:
    allNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    shuffle(allNumbers)

randNumber = allNumbers.pop()

Best wishes Jens

1 Like

Hi Jens,

this might be a not so smart question, but what exactly do you mean by “outside” of the loop? Within the routine right before the loop? If so, in which tab?

Thanks again!

You should be able to put these lines in the Begin Experiment tab of the code you have.

Ok, so I now have a code element within the baseline task loop.

I put the first two lines in the Begin Experiment tab:

allNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
shuffle(allNumbers)

and the third line in the Begin Routine tab:

randNumber = allNumbers.pop()

and I get this error:

randNumber = allNumbers.pop()
IndexError: pop from empty list
##### Experiment ended. #####

Do you get that error straight away or after the list has been used up once?

The error appears after the list has been used once (there is a timer on the list of 6-8 s, just in case that is relevant).

In that case you need to rebuild the list when it’s empty.

For example

if len(allNumbers) == 0:
     Put the code from Begin Experiment here but tabbed in