2

From a given array I need a list of all the 1-element-swap list. I dont know how is this called so better if I explain it with an example.

For example. For a given array :

array = [1,2,3,4]

I need the output:

[2,1,3,4]
[3,2,1,4]
[4,2,3,1]
[1,3,2,4]
[1,4,3,2]
[1,2,4,3]

This means if K is the size of the array, I must get a (K(K-1))/2 output arrays.

In the example above, K=4 so 4(3)/2=6 output arrays.

I really dont know how to do it. I know there's the itertools function, but if I use itertools.permutations(array) I don't get my desired solution as this shows me all the permutations, and I only need a list of the "1 swap element" list.

1
  • Have you tried simply looping through the values and swapping each of them with all other values? And then removing doubles obviously. Commented Apr 13, 2015 at 15:27

2 Answers 2

2

Something like this should get you started:

>>> x = [1,2,3,4]
>>> for i in xrange(len(x)):
...     for j in xrange(i + 1, len(x)):
...         y = x[:]
...         y[i], y[j] = y[j], y[i]
...         print y
... 
Sign up to request clarification or add additional context in comments.

1 Comment

If you are using python 3 replace xrange with range, and print y with print(y);
0

Quite simply:

array = [1,2,3,4]

# swaps to elements, and return the resulting array
def swap(x, i, j):
    x[i], x[j] = x[j], x[i]
    return x

arrays = [swap(array[:], i, j) 
                 for i in range(len(array))
                 for j in range(i + 1, len(array))]

print(arrays)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.