从Python和C中的列表中查找一个转置排列

时间:2014-12-26 13:03:24

标签: python c list

我的输入为A = [ 2,3,4,1]

输出只是A中元素的所有可能排列,可以通过单个转置(单个翻转两个相邻元素)操作来完成。所以输出是:

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

如何在Python中执行此操作?和/或 C

修改 允许圆形转置。因此[2,3,4,1] ==>允许[1,3,4,2]和有效输出。

4 个答案:

答案 0 :(得分:4)

A = [2,3,4,1]

res = []
for i in range(len(A)):
    temp = A[:]
    temp[i], temp[i-1] = temp[i-1], temp[i]
    res.append(temp)

print res

结果:

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

答案 1 :(得分:2)

不是开箱即用的解决方案,但非常简单易懂

a = [ 2,3,4,1]                           # Initialize the array with input
o = []                                   # Have a empty list to hold the output
n = len(a)                               # Get the length of the array
for i in range(n):                       # Loop 'n' times 
    x=a[:]                               # Get a copy of the array. '[:]' is the  slicing operator. '[:]' means to copy all the elements of the list to 'x'
    x[i],x[(i+1)%n] = x[(i+1)%n],x[i]    # Swap the adjacent two elements. We require '%' modulus operator to make the list circular
    o.append(x)                          # Add the changed list to the output array
print o                                  # Print the output array

输出

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

答案 2 :(得分:1)

def swapped(l, p1, p2):
    r = l[:]
    r[p1], r[p2] = r[p2], r[p1]
    return r

A = [2, 3, 4, 1]
transp = [swapped(A, i, (i+1)%len(A)) for i in range(len(A))]

答案 3 :(得分:1)

这里有点不同:

def swapper(a, j, k):
    return [a[k] if i == j else a[j] if i == k else a[i] for i in range(len(a))]

def transpositions(a):
    length = len(a)
    return [swapper(a, j, (j+1)%length) for j in range(length)]

print(transpositions([2, 3, 4, 1]))

这是一个更具迭代性的解决方案:

from itertools import izip, tee

def swaps(length):
    a, b = tee(range(length))
    next(b, None)
    for pair in izip(a, b):
        yield pair
    yield (length-1, 0)

def swapper(a, i, j):
    a[i], a[j] = a[j], a[i]
    yield a
    a[i], a[j] = a[j], a[i]

def transpositions(a):
    return [r for i, j in swaps(len(a)) for r in swapper(a, i, j)]

print(transpositions([2, 3, 4, 1]))