Alex Johnson Alex Johnson - 26 days ago 7
Python Question

Same values in two lists (pairs)

So I need to have a list going where I have 1 list with a load of values between 1 and 8 randomly generated and another list with a load of values between 1 and 8 randomly also. I have managed to do this on my code below:

from random import *
listA = []
listB = []
inp = int(input('Number of values generated'))
for x in range(0,inp):
num = randint(0,8)
listA.append(num)
if num == 0:
numB = randint(1,8)
else:
numB = randint(0,8)
listB.append(numB)
print(listA)
print(listB)


The value in the first list can't be 0 and the value in the seond list can't be zero too on the same trial. I have this already in my code. However this is the problem I have.

[4, 5, 2, 5, 1]

[1, 2, 3, 2, 4]

In listA, the 5 is produced twice and the 2 below it on the second list is produced twice also. I can't figure out a solution to get these out from my lists, when they create a pair like this.
Thanks.

Answer

You can use a helper function as below to generate a unique number that is not in the list and append that to the list.

This should work for you:

def generateUnique(list, start, end):  # Helper Function to generate and return unique number not in list
    num = randint(start, end)
    while num in list:  # loop will keep generating a value, until it is unique in the given list
        num = randint(start, end)
    return num


from random import *
listA = []
listB = []
inp = int(input('Number of values generated'))
for x in range(0,inp):
    num = generateUnique(listA, 0, 8)
    listA.append(num)
    if num == 0:
        numB = generateUnique(listB, 1, 8)
    else:
        numB = generateUnique(listB, 0, 8)
    listB.append(numB)

print(listA)
print(listB)

Hope this helps!