-1

I have two lists list1=['A','B','C'] list2=['1','2','3'] I need a long list (combined by these 2 lists) of length 'n' without

  1. any same pair consecutively ['A1','A1','C3','B2','B2',.....]
  2. any same element of list1 consecutively ['A1','A2','A3','B1','B2',.......]
  3. any same element of list2 consecutively ['A1','B1','C1','A2','B2',.......]

I want the elements of combined list in any order but without duplicates next to each other. In other words, exactly like this for this example, ['A1','B2','C3','A2','B3','C1','A3','B1','C2','A1','B2','C3'.....]

Can someone please help me. I am looking for an answer since 2 days.

Edit:

I tried itertools method products.

newlist = [ n[0]+n[1] for n in list(itertools.product(list1,list2))]

#This gives the exact permutation of elements I need but not in the order I wish.

newlist = ['a1','a2','a3','b1','b2','b3','c1','c2','c3']

#Then, I used nested loops,

#To swap consecutive pairs elements in the newlist for ind,n in enumerate(newlist): while n == newlist[ind-1]: for ind,n in enumerate(newlist): while n == newlist[ind-1]: newlist[ind-1],newlist[ind-2] = newlist[ind-2],newlist[ind-1]

#To swap consecutive list1 elements in the newlist for ind,n in enumerate(newlist): while n[0] == newlist[ind-1][0]: for ind,n in enumerate(newlist): while n[0] == newlist[ind-1][0]: newlist[ind-1],newlist[ind-2] = newlist[ind-2],newlist[ind-1]

#To swap consecutive list2 elements in the newlist for ind,n in enumerate(newlist): while n[1] == newlist[ind-1][1]: for ind,n in enumerate(newlist): while n[1] == newlist[ind-1][1]: newlist[ind-1],newlist[ind-2] = newlist[ind-2],newlist[ind-1]

Apparently, It works well with list with more than 3 elements. But not for the lists with length 3 and 2 respectively.

Moriartyalex
  • 64
  • 1
  • 5

3 Answers3

0

I have found a solution to what you want. A comment pointed by jrook showed a discussion similar to this but in their case it did not check to make sure it followed all the parameters you want. So i went ahead and wrote a little code for it.

import itertools

list1 = ["A","B","C"]
list2 = ["1","2","3", "4"]

if len(list1) < len(list2):
    x = list1[:]
    list1 = list2
    list2 = x
    list3 = [zip(x,list2) for x in itertools.permutations(list1,len(list2))]
    new = []
    for lis in list3:
        for i in lis:
            new.append(i[1] + i[0])    

else:
    list3 = [zip(x,list2) for x in itertools.permutations(list1,len(list2))]
    new = []
    for lis in list3:
        for i in lis:
            new.append(i[0] + i[1])



final = []
final.append(new[0])
new = new[1:]

def add_to(new, final):
    if final[-1][0] != new[0][0] and final[-1][1] != new[0][1] and final[-1] != new[0]:
        final.append(new[0])
        new = new[1:]
    else:
        b = new[0]
        new = new[1:]
        new.append(b)

    return new, final



while new != []:
    new, final = add_to(new, final)


print(final)

the variable final is a list that will make sure that all the rules u want are followed, i.e: no duplicates, none of the same consecutive letter or number. Hope this is what you were looking for. I edited this so that now you can have the second or first list be of longer length and it will work just fine.

pm980
  • 123
  • 11
  • Just to add on to this post remember that list1 and list2 can be changed to whatever lists you want. And the 4th line is from the discussion jrook pointed you to, which makes a list of all the combinations you want as tuples. Ex. [("B", "1"), ("A", "2") ...] I just took this list and created it to become what you are having trouble with. – pm980 Feb 04 '20 at 20:13
  • It works well among lists with same lengths. I tested list1 with 3 elements and list 2 with 4 elements I am getting list index out of range error at line 15 final.append(new[0]). When I tried with list2 – Moriartyalex Feb 05 '20 at 11:32
  • oh ok ill take a look – pm980 Feb 05 '20 at 14:01
  • I found the error, for some reason if list 2 is longer there is an issue so what I did was if it is it switches with list one and then is just added differently. – pm980 Feb 05 '20 at 14:08
0
#Join the given list
list(map("".join,(zip(["A", "B", "C"], ["1","2","3"]))))

# Given your list
l3=["A1","B1","C1","A2","B2"]
l2=["A1","A2","A3","B1","B2"]
l=["A1","A1","C3","B2","B2"]

# set() data structure ensure no duplicate
list(set(l))+list(set(l2))+list(set(l3))

# output should be:
# ['B2', 'C3', 'A1', 'B2', 'A3', 'A2', 'B1', 'A1', 'C1', 'B2', 'A2', 'B1', 'A1']

Hope this help.

  • `list(set(l))+list(set(l2))+list(set(l3))` seems needlessly awkward, wouldn't `list(set(l + l2 + l3))` do the job? Also, `l` is one of the variable names that PEP 8 explicitly says should be avoided. See: https://www.python.org/dev/peps/pep-0008/#names-to-avoid. – AMC Feb 04 '20 at 22:31
  • The last 2 elements in your output does not satisfy my 3rd condition. 1 is in consecutive indices. – Moriartyalex Feb 05 '20 at 10:29
0
#declaring 2 lists
    x=['a','b','c']
    y=[str(n) for n in range(1,5)]


    li=[]
    #Creating the pairs by shuffling two lists
    if len(x)>len(y):
        for m in range(len(x)):
            for n in range(len(y)):
                li.append(x[m]+y[n-1])
                m-=1
    else:
        for m in range(len(y)):
            for n in range(len(x)):
                li.append(y[m]+x[n-1])
                m-=1

    def pair_check(li):
        for ind,val in enumerate(li):
            if li[ind]==li[ind-1] or li[ind][0]==li[ind-1][0] or li[ind][1]==li[ind-1][1]:
                return True

    def pair_swap(li):
        for ind,val in enumerate(li):
            while li[ind]==li[ind-1] or li[ind][0]==li[ind-1][0] or li[ind][1]==li[ind-1][1]:
                li[ind-len(x)],li[ind]=li[ind],li[ind-(len(x))]

    #functions that verifies and swaps the pairs in combined list
    while pair_check(li):
        pair_swap(li)

    print (li)
    #Now the list li contains the list satisfies all the 3 conditions.
Moriartyalex
  • 64
  • 1
  • 5
  • I found the answer. It is not applicable for the 2x2 matrix of lists, since it is logically impossible. ['a1','a2','b1','b2'] -- violates rule 2 ['a1','b2','a2','b1'] -- violates rule 3 ['a1','b2','a1','b2'] -- Not the pairs I want. – Moriartyalex Feb 07 '20 at 19:09