2

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)
Alroc
  • 105
  • 1
  • 1
  • 5

1 Answers1

1

You're getting infinite recursion because you never reassign any of the variables when you call the functions recursively. So the same if condition succeeds, and you recurse again.

But picking a random element repeatedly is not a good way to do this. Shuffle list1, then append each element of list1 to the corresponding element of list2.

random.shuffle(list1)
for i, el in enumerate(list1):
    list2[i].append(el)
Barmar
  • 741,623
  • 53
  • 500
  • 612