简体   繁体   中英

generate random number that excludes one number from the range python

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 .

您可以使用random.choice

move =  random.choice([1, 3, 4, 5, 6, 7, 8, 9, 10])

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

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.

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]))

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM