I’m having trouble explaining this so please bare with me.
I have several lists and I want to write a python script that picks an item at random from the first list, then checks that result against a "fail list," if the item isn’t on the "fail list" I want to move to the next list and do the same thing until it fails.
#Go through these lists one by one, picking random item.
action_heros = ['thor', 'batman', 'spiderman', 'superbart']
friends = ['joey', 'feebee', 'rachael', 'dog']
himym = ['robin', 'marshall', 'ted', 'lily', 'barney']
# fail list
simpsons = ['bart', 'homer', 'marg', 'superbart', 'dog', 'barney']
#This is how I've been trying to solve it, but I can't get the code to move to the second or third attempt
# pick a random word from the lists
rand_action_hero = random.choice(action_heros)
rand_friend = random.choice(friends)
rand_himym = random.choice(himym)
#run the random word from each list against the checklist one by one until it fails.
if rand_action_hero in simpsons:
print('failed at actionheros')
#if the random word isn't in simpsons I want it to pick a new random word and try against friend, then himym
Thanks for any help, I’m still learning to code so it means a lot!
>Solution :
If you know about hash sets, I would use a set for the fail list for faster lookups although it is unnecessary.
Other than that, this code should work.
import random
#Go through these lists one by one, picking random item.
action_heros = ['thor', 'batman', 'spiderman', 'superbart']
friends = ['joey', 'feebee', 'rachael', 'dog']
himym = ['robin', 'marshall', 'ted', 'lily', 'barney']
# fail list
simpsons = set(['bart', 'homer', 'marg', 'superbart', 'dog', 'barney'])
# loop until it breaks
while 1:
rand_action_hero = random.choice(action_heros)
print(rand_action_hero)
if rand_action_hero in simpsons:
print("random action hero in fail list")
break
rand_friend = random.choice(friends)
print(rand_friend)
if rand_friend in simpsons:
print("random friend in fail list")
break
rand_himym = random.choice(himym)
print(rand_himym)
if rand_himym in simpsons:
print("random himym in fail list")
break