Home > Net >  How can I generate a new, random value in a list in Python 3 repeatedly until all values have been r
How can I generate a new, random value in a list in Python 3 repeatedly until all values have been r

Time:01-17

from easygui import *
from time import *
from statedict import *
import random

correctnum = 0
questionsanswered = 0
print("Indian Map Quiz v1")
sleep(0.5)
print("Note all features might not work correctly, this is a work in progress.")


msgbox("Welcome to Indian Map Quiz", "INDIA", "Continue")

title = "Guess The State"
msg = "What Indian state is this?"

stateFactList = [APdict, ARdict, ASdict, BRdict, CTdict, GAdict, GJdict, HPdict, HRdict, JHdict,
                 KAdict, KLdict, MHdict, MLdict, MNdict, MPdict, MZdict, NLdict, ODdict, PBdict,
                 RJdict, SKdict, TGdict, TNdict, TRdict, UPdict, UTdict, WBdict]




stateID = random.choice(stateFactList)
print(stateID["state"])
stateQuestion = buttonbox(msg=msg, title=title, choices=stateID["choices"], image=stateID["image file"])

if stateQuestion == stateID["correct"]:
    print("it's correct")
    correctnum  = 1
    questionsanswered  = 1
else:
    print("incorrect")
    questionsanswered  = 1

Here is the code, essentially when you run the program, it should randomly pick a state and provide some multiple choice answers based on the state. It randomly picks a state from the stateFactlist list and matches it with a dictionary stored in another file. Whenever the user answers a question, I want it to generate a new, random state to be displayed to the user, along with the respective multiple choice answers, but I can't find a way to implement it. Help is appreciated.

CodePudding user response:

To help clear up the confusion, random.sample() includes a parameter, k, which lets you specify the number of unique elements to randomly choose from the specified sequence. It can work well for what OP has in mind. Here is a simplified example for illustration purposes:

import random

arr = ["A", "B", "C", "D"]
for x in random.sample(arr, k=len(arr)):
    print(x)

Output:

C
D
A
B

CodePudding user response:

Just shuffle the list, then iterate normally.

randome.shuffle(stateFactList)
for state in stateFactList:
    ...

CodePudding user response:

you can remove the already picked element from the list for fair share

Like below example:

>>> a = [1,2,3,4,5]
>>> choice = random.choice(a)
>>> choice
4
>>> a.remove(a.index(choice))     # removes 4 from the list
>>> a
[1, 2, 4, 5]
>>> choice = random.choice(a)
>>> choice
2
  • Related