-3
firstrandom = random.randint(1,2)
secondrandom = random.randint(1,2)

I just need the secondrandom variable to not equal the firstrandom variable, but I don't know how to.

martineau
  • 119,623
  • 25
  • 170
  • 301
eric424
  • 3
  • 2
  • 1
    I think this is what you're looking for: https://stackoverflow.com/questions/13628725/how-to-generate-random-numbers-that-are-different – melbok Aug 25 '20 at 18:47
  • 1
    In this case, it's easy. Whichever one `firstrandom` is, `secondrandom` is the *other* one. `secondrandom` isn't actually random; it's a function of the first value. – chepner Aug 25 '20 at 18:48
  • The second number isn't random if there's a limitation put on its value. A simple solution is, after getting the first number, loop until you get something that's not equal to it from `randint()`. – martineau Aug 25 '20 at 20:33
  • @martineau, simple, but less efficient than using `random.sample`. – Chris Aug 01 '23 at 00:50

2 Answers2

2

Some potential options:

  1. In this case, since both variables can only either be 1 or 2, just make secondrandom = 1 + (firstrandom % 2).
  2. Put the second randint in a loop and only exit the loop when the value is different from firstrandom.
  3. Enumerate the valid values first, then pick a random.sample of the allowed values.
0x5453
  • 12,753
  • 1
  • 32
  • 61
-1

You could try this function, it returns a pair of two random integers that are not equal to each other:

import random
def randomPair(start, stop):
    n1 = random.randint(start, stop)
    n2 = random.randint(start, stop)
    if start!=stop:
        while n1 == n2: n2 = random.randint(start, stop) 
    return n1, n2
dieSdiesneB
  • 1
  • 1
  • 1