Home > OS >  How to select different option regardless of randomized variable
How to select different option regardless of randomized variable

Time:12-18

The question might be a little misleading, as there are no exact words to express my query shortly. What I want to do is make a random variable, and according to it pick one name from, let's say, 5 options. Then, pick another name from the same pool of options, however without being the same as the first name.

For example, if I have 5 students (John, Mary, Doug, Brandon, and Ava) and I want to choose between two of them, but not pick the same student twice.

Here is how I proceeded to choose the first variable using random.randint() function.

subj = random.randint(1, 3)
    if subj==1:
        subj1=='John'
    elif subj==2:
        subj1=='Mary'
    elif subj==3:
        subj1=='Doug'

(Note: value names are just an example)

Now for the second value, I have had some ideas, however I don't know how to complete it. Any help is appreciated!!

Have a great day.

P.S.: As far as I know there are no other similar questions, or at least I couldn't find any. If there are, please redirect me there.

CodePudding user response:

How about sampling directly from your list? The code below will select two students from your list at random.

import random

students = ['John', 'Mary', 'Doug', 'Brandon', 'Ava']
selection = random.sample(students, 2)

# Optional: Unpacking list
subj1, subj2 = selection

CodePudding user response:

You can use itertools.permutations() along with random.shuffle() like this

from itertools import permutations as perm
from random import shuffle

names = ["John", "Mary", "Doug", "Brandon", "Ava"]
res = list(perm(names, 2))
shuffle(res)

print(res.pop())

First, the names stores all the names in a list, and the permutations iterates through the list and returns all the permutations of 2 names each; this is stored as a list of tuples in res and the shuffle does what it says, it shuffles the list in a random order, and at last the pop returns the last item in it.

CodePudding user response:

you can do this:

 import random
 names = ['John','Mary','Doug','Ted','Mary']
 idx = random.sample(range(len(names)), len(names))
 for index in idx:
    print(names[index])

This will give you a list of unique generated random indices. based on this you can select the names(let's say you have all of them in a list) and pick them based on idx.

  • Related