jeudi 2 janvier 2020

Creating a random list from a list without repeating items

I am trying to create a new list of lists from a list. The goal is to randomly pick a name from listA and add it in a specific spot in listB. However, names should not be repeated in listB.

Here is my attempt. Sometimes it works and other times I get "RecursionError: maximum recursion depth exceeded in comparison". It traces back to yFinder or zFinder.

Any advice would be appreciated. Thanks!

import random

listA = ["Foo","Spam","Eggs"]
listB = [["A"],["B"],["C"]]

x = random.sample(listA,1)
y = random.sample(listA,1)
z = random.sample(listA,1)

def xFinder():
  x
  listB[0].append(x)

def yFinder():
  y
  if y != x:
    listB[1].append(y)
  else:
    yFinder()

def zFinder():
  z
  if z == y:
    zFinder()
  elif z == x:
    zFinder()
  else:
    listB[2].append(z)   

xFinder()
yFinder()
zFinder()

print(listB)



Aucun commentaire:

Enregistrer un commentaire