0

I am generating a number from the range of 1 to 10 but would like to exclude the number 2 from that range i have no idea how to go about doing this.

This is what i have so far.

python file

move =  random.randint(1, 10)

So to round of: I want to generate numbers between 1 to 10 and exclude number 2.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
o3203823
  • 63
  • 1
  • 11
  • Possible duplicate of [How to randomly select an item from a list?](https://stackoverflow.com/questions/306400/how-to-randomly-select-an-item-from-a-list) – mrk Dec 14 '18 at 05:00

5 Answers5

4

You could use random.choice:

move =  random.choice([1, 3, 4, 5, 6, 7, 8, 9, 10])
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • Olivier's answer is probably better for this *specific* question but won't scale well if the rules are complex (like all primes less than a hundred). In that case, `choice` is the better , well choice, I guess :-) – paxdiablo Dec 14 '18 at 04:48
4

You can generate a random value from 1 to 9 instead and shift it by one if it is bigger or equal to 2.

value =  random.randint(1, 9)

move = value if value < 2 else value + 1

Mathematically, you want to select a random element in a set of 9 elements. All you need to do is to identify the element 3 with 2, 4 with 3 and so on. In probability, this is what we call a random variable.

A random variable is defined as a function that maps the outcomes of unpredictable processes to numerical quantities.

This strategy of using a mapping is especially useful when your set is big and generating it would be costly, but the mapping rule is fairly simple.

Improvement:

It was pointed out by U9-Forward that in this case the mapping can be made slightly more efficient. It suffices to map 2 to 10.

value =  random.randint(1, 9)

move = value if value != 2 else 10
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
1

Or do another way of conditioning like Olivier's answer:

value =  random.randint(1, 9)
move = 10 if move==2 else move

Then move will never be 2 again.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

An obvious and easy interpretable path would be to exclude the 2 by a while-loop and just drawing numbers, using the function you mentioned, until the 2 gets not picked. This is yet highly inefficient but a work-around you can reach with basic programming concepts.

The more direct way would be to define your list more precisely, meaning without the 2 and making use of the random.choice function:

import random
print(random.choice([1, 3, 4, 5, 6, 7, 8, 9, 10]))
mrk
  • 8,059
  • 3
  • 56
  • 78
0

You can exclude number 2 using "while"

move =  random.randint(1, 10)

while move == 2:
    move = random.randint(1, 10)

This code will generate random number until it won't be "2"