Home > Back-end >  Rearrange python list to avoid any position matches
Rearrange python list to avoid any position matches

Time:12-20

I have 2 lists list1 and list2. How would I rearrange list1 (without rearranging list2) so that there are no matches on any positions eg:

UNDESIRED: list1 = [‘A’, ‘B’, ‘C’] list2 = [‘X’, ‘B’, ‘Z’] as you can see the B is on the same position, 1, in both lists…so I would then like to rearrange list1 to list1 = [‘B’, ‘A’, ‘C’] or any other order where there are no positional matches with list2 WITHOUT rearranging list2

CodePudding user response:

You could do this with the help of the itertools module. There may be better / more efficient mechanisms. Note that the process() function will return None when there is no possible solution.

import itertools

def process(L1, L2):
    for s in set(itertools.permutations(L1, len(L1))):
        if all([a != b for a, b in zip(s, L2)]):
            return s
    return None

list1 = ['A', 'B', 'C']
list2 = ['X', 'B', 'Z']

print(process(list1, list2))

CodePudding user response:

from itertools import permutations

def diff(list1, list2):
    for item in permutations(list1, len(list1)):
        if all(map(lambda a, b: a!=b, item, list2)):
            return list(item)
    return None

list1 = ['A', 'B', 'C']
list2 = ['X', 'B', 'Z']

result = diff(list1, list2)
if result:
    print(result, 'vs', list2)
['A', 'C', 'B'] vs ['X', 'B', 'Z']

CodePudding user response:

I solved it using this piece of code - however, as noted above, there are many possible cases where this very solution may not work. In this very case, you can try this:

import random
list1 = ['A', 'B', 'C']
list2 = ['X', 'B', 'Z']
for i in list1:
    for j in list2:
        if i == j in list2:
            while list1.index(i) == list2.index(j):
                list1.remove(i)
                z = len(list1)
                rand = random.choice(range(z))
                list1.insert(rand, i)
print(list1, list2)

Also, note that you use quite weird apostrophes inside the list: instead of ' or ". AFAIK, Python won't be able to comprehend them correctly.

  • Related