Bartek Spitza Bartek Spitza -4 years ago 61
Python Question

How could I shuffle a list to this rule?

I am trying to make an algorithm to shuffle a list and then make a new list of all the combinations according to this rule:

You are only allowed to swap one pair. For example:

array = [1, 2, 3]
[3, 2, 1] #number at index 0 switched with number at index 2

Any thoughts on how to write it?

Saschas code worked well. I wrote this code before asking the question:

sols = []
for i in range(len(a)):
for j in range(len(a)):
a[i] = a[j]
a[j] = a[i]

I was aware that I would get some identical elements in the list because of unordered pairs but it just created a list full of identical elements. Any thoughts why?

Answer Source
sols = []
for i in range(len(array)):
    for j in range(i+1, len(array)):    # symmetry-reduction -> ordered pairs
        sol = array[:]                  # copy list
        sol[i], sol[j] = sol[j], sol[i] # swap
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download