0

I am trying to generate a random number.

import random
print(random.randint(1,10))

Would I be able to generate a number between 1-10 but without ever generating x?

For example x = 3

TNTDoctor
  • 15
  • 5

3 Answers3

5

Three approaches:

  1. Loop until it's valid:

    while (val := random.randint(1, 10)) == 3:  # Python 3.8+, pre-3.8 is more verbose
        pass
    print(val)
    
  2. Generate from a smaller range, then increment all numbers equal to or higher than the excluded value:

    val = random.randint(1, 9)
    if val >= 3:
        val += 1
    print(val)
    
  3. Create a sequence of the numbers you allow, and use random.choice (probably the best solution if you're doing this many times; make the sequence once, then reuse it after):

    # Done once (must convert back to sequence from set, choice only works with sequences)
    values = tuple(set(range(1, 11)) - {3})
    
    # Done as often as you like
    print(random.choice(values))
    
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
3

Onliner, using range and sets:

x = 3
print(random.choice(list(set(range(1,11))-{x})))
# list(set(range(1,11))-{x})) -> [1, 2, 4, 5, 6, 7, 8, 9, 10]
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
2

If you use choice you can provide a list of acceptable values:

random.choice([[1,2,4,5,6,7,8,9]])

Flow
  • 551
  • 1
  • 3
  • 9