I have 2 lists of random numbers that range from 0-7 that I want to pair up
listA = random.sample(range(8), 8)
listB = random.sample(range(8), 8)
However, I want to make sure that the number 1 in listA never pairs with itself or the number 4 from listB.
for a,b in zip (listA, listB):
if a==b:
random.shuffle(giver)
if a==1 and b==4:
random.shuffle(giver)
How do I ensure that both of those conditions are true for my lists?
Thank you for your time!
I came up with this:
import itertools
import random
list_a = random.sample(range(8), 8)
list_b = random.sample(range(8), 8)
it1 = itertools.cycle(list_a)
it2 = itertools.cycle(list_b)
def gen_pairs():
count = 0
while count < 8:
x, y = next(it1), next(it2)
if y == list_a[1] or x == list_b[4]:
continue
yield x, y
count += 1
print(list_a[1])
print(list_b[4])
for _ in range(20):
res = list(gen_pairs())
assert (list_a[1], list_a[1]) not in res
assert (list_b[4], list_b[4]) not in res
I hope I understood correctly and that this is of help:
import random
listA = random.sample(range(8), 8)
listB = random.sample(range(8), 8)
## This first search is just for listA[0]
zipped_list = []
good_match = False
while good_match == False:
candidate = random.choice(listB)
if listA[0] != candidate and listA[0] != listB[3]:
zipped_list.append([listA[0], candidate])
good_match = True
## Now we find numbers to match with the rest of listA
for num in listA[1:]:
good_match = False
while (good_match == False):
candidate = random.choice(listB)
if num != candidate:
zipped_list.append([num, candidate])
good_match = True
print(zipped_list)
Input example:
listA: [7, 4, 2, 1, 3, 0, 5, 6]
listB: [0, 3, 5, 1, 4, 2, 7, 6]
Output example: First element of listA (7) does not match with listB[0] or listB[4], and other numbers have not matched with themselves.
[[7, 1], [4, 1], [2, 6], [1, 0], [3, 2], [0, 2], [5, 2], [6, 2]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.