How to randomize the order of elements of a list w

2020-06-16 02:36发布

I have a python list of strings, let's say:

elems = ["A", "B", "C", "D"]

I want to create a new list whose elements are each element of elems repeated a fixed number of times (let's say twice), in a random order, but while making sure that two consecutive elements never have the same value.

For example, ["D", "B", "A", "B", "D", "C", "A", "C"] is a good result. ["D", "B", "A", "B", "D", "C", "C", "A"] is not (C is repeated in 6th and 7th position).

The simplest idea is probbaly just:

ans = 2*elems
random.shuffle(ans)

and then some code to take care of the repetitions, but all the solutions I can think of involve potentially infinite loops. Is there a simple and reliable way to do that ?

Thanks.

4条回答
混吃等死
2楼-- · 2020-06-16 03:04

You could make a function that checks if two consecutive values in a list x are the same:

def compareConsecutive(x):
    for i in x:
        if i == x[x.index(i)+1]:
            return False

Then shuffle the list in a while loop until compareConsecutive() stops returning False:

while compareConsecutive(ans) == False:
    random.shuffle(ans)

This could take a while with a long list, since random.shuffle() could keep generating lists that have consecutive values in them, but it will work eventually :)

查看更多
欢心
3楼-- · 2020-06-16 03:05

I think this will work, although it is not so elegant.

import random

elems = ['a','b','c','d']
length = len(elems)

l = []

for i in range(2):
    random.shuffle(elems)
    l.extend( elems )
    if i > 0 and l[ i*length ] == l[ i*length - 1 ]:
        l[i*length-2], l[i*length-1] = l[i*length-1], l[i*length-2]

print l 
查看更多
We Are One
4楼-- · 2020-06-16 03:09

I think this could be an algorithm for doing what you want:

let R be your result list

  1. pick a random element e from elems, and append e to R
  2. let elems_1 = elems \ e, i.e. remove e from elems
  3. pick a random element e_1 from elems_1, and append e_1 to R
  4. let elems_1 = elems \ e_1, i.e. remove e_1 from elems
  5. repeat from step 3 until R is long enough
查看更多
Bombasti
5楼-- · 2020-06-16 03:16

I am assuming that the input list has distinct elements.

import random

def randomize_carefully(elems, n_repeat=2):
    s = set(elems)
    res = []
    for n in range(n_repeat):
        if res:
            # Avoid the last placed element
            lst = list(s.difference({res[-1]}))
            # Shuffle
            random.shuffle(lst)
            lst.append(res[-1])
            # Shuffle once more to avoid obvious repeating patterns in the last position
            lst[1:] = random.sample(lst[1:], len(lst)-1)
        else:
            lst = elems[:]
            random.shuffle(lst)
        res.extend(lst)
    return res

for i in range(10):
    print randomize_carefully(["A", "B", "C", "D"])

Some output:

['B', 'C', 'D', 'A', 'C', 'A', 'D', 'B']
['B', 'D', 'C', 'A', 'C', 'B', 'A', 'D']
['C', 'B', 'D', 'A', 'B', 'C', 'D', 'A']
['B', 'D', 'A', 'C', 'A', 'B', 'D', 'C']
['D', 'C', 'A', 'B', 'C', 'D', 'A', 'B']
['C', 'D', 'A', 'B', 'D', 'C', 'A', 'B']
['D', 'A', 'C', 'B', 'C', 'A', 'B', 'D']
['C', 'D', 'A', 'B', 'C', 'D', 'A', 'B']
['C', 'B', 'A', 'D', 'A', 'B', 'D', 'C']
['B', 'D', 'A', 'C', 'A', 'D', 'C', 'B']
查看更多
登录 后发表回答