1 votes

How to exclude certain numbers with random.randint?

Will there be any possibility to exclude for example: the number 50, 99, 80 for so that it is not printed?

x = (random.randint(1, 100))
print(x)

4voto

I copy exactly what it says in this question:

from random import choice

print(choice([i for i in range(0,9) if i not in [2,5,7]]))

In your case print(choice([i for i in range(1,101) if i not in [50,99,80]]))

As César adds in the comments, the range that returns random.randint is inclusive, so for it to include 100, you should put 101.

1 votes

In fact, in his case it would be range(1, 101) because the range used by random.randint is inclusive.

1 votes

Right @César, I modify it, thank you very much.

3voto

Patricio Moracho Points 24098

A similar but somewhat different approach to Adrian's answer, provided the list of cases is relatively small, is:

  • generate a list of all possible values to choose from
  • generate a random value but to use as a list selection index.

    import random
    elementos = [n for n in range(0, 101) if n not in [50, 99, 80]]
    x = elementos[random.randint(0, len(elementos))]

It may eventually be more optimal if the number of excluded values is significant.

0 votes

The last part should start from 0, it would be elementos[random.randint(0, len(elementos) - 1)] but you are excluding the first element, and at the end restartle one so that it does not give a IndexError . Remember that these are positions in a list.

1 votes

@César, that's totally true, I was in R mode (where the positions start from 1).

1 votes

So far I don't understand why the hell the R guys came up with the idea of starting from 1. I don't use it very often but for the master's course they taught us a little bit and we were all going crazy about this decision R made.

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X