0

I am trying to create a list from multiple repeating elements (type does not really matter as long as they are all the same) in which a given element does not repeat itself back-to-back. Or put differently, there should be no repetitions from index n to index n+1 in the resulting list.

More specifically, I have for example...

shape_typesA = [1, 1, 2, 2]
shape_typesB = [2, 2, 1, 3]

...and I would like to randomly combine them in a list like so:

shape_typesALL = [2, 1, 2, 1, 2, 1, 2, 3]

Each element of each original list (i.e. shape_typesA / shape_typesB) is only allowed to appear once in the resulting list (i.e. shape_typesALL). Lists have typically the same length. If there is no solution, an error should be raised.

What is the best solution for this problem?

MichlF
  • 139
  • 1
  • 8
  • So does it make any difference at all _which_ input list an element is from, or is the problem entirely equivalent to choosing an appropriate permutation of a single input list containing all the elements? – alani Jul 11 '20 at 23:25
  • @alaniwi Ideally it matters but choosing an appropriate permutation of a single input list containing all elements would also suffice for my current cases. – MichlF Jul 11 '20 at 23:33

3 Answers3

0
from random import shuffle
list = shuffle(list)


def no_repeats_list(old_list):
    new_list = []
    for i in range(len(old_list) - 1):
        if old_list[i] != old_list[i+1]:
            new_list.append(old_list[i])
    new_list.append(old_list[-1])
    return new_list
Rushil S
  • 78
  • 6
  • This is a good approach but will more often than not find a solution in which not *all* elements from `old_list` end up in `new_list`. – MichlF Jul 12 '20 at 04:56
0
  • segregate the items into containers where all items in a container are equal
  • develop a round robin sequence based on length.
    • identify length differences of 2 or more from one container to the next in the sequence -- gaps
  • start with the longest container and remove an item - keep track of list lengths
  • continue in the sequence removing an item from the next container
    • use items (out of sequence) from the containers with the least or most number of items to try and maintain length differences of one or less from one container to the next
wwii
  • 23,232
  • 7
  • 37
  • 77
0

lists can have duplicate values but sets can not have duplicate values so turn the combined list to a set and afterward turn it back to list.

check out the below code.

shape_typesA = [1, 1, 2, 2]
shape_typesB = [2, 2, 1, 3]
shap = shape_typesA+shape_typesB
shap = set (shap)
shap = list(shap)
print (shap)

In output you will get a list with no repeating characters.

Raviraja
  • 1
  • 2
  • This will remove all duplicates from the list. However, I need the final list to have all elements from each original list (whether duplicate or not). They should just not be the same from n to n+1. – MichlF Jul 12 '20 at 04:59