如何生成对索引值有约束的排列列表?

时间:2019-11-08 11:28:35

标签: python python-3.x

我需要使用约束来创建给定列表的排列,

given input sequence=(x_0, x_1, x_2,..) and an integer k, the output sequence=(x_perm(0), x_perm(1), x_perm(2),..) with perm(i)< i+k. 

For example for k=2 that means;

   x_perm(0) is either x_0 or x_1

   x_perm(1) is either x_0, x_1 or x_2

Another example for input=[3,4,5] and k=2 is:

output=[4,3,5] is a valid permutation, but [5,4,3] is not since x_perm(0) cannot be x_2.
def spec_perm(iterable, k):
    import random
    perm=[0]*len(iterable)
    for i in range (0,len(iterable)):
        perm[i]=random.choice(iterable[0:k+i])
    return perm

我已经尝试过此代码,但是随机选择包含重复项,因此不会产生期望的结果。

最后,我需要获取所有有效的排列。

2 个答案:

答案 0 :(得分:0)

我认为这是您感兴趣的。 Python提供了直接的方法来查找排列。这些方法位于itertools软件包中。

导入itertools包以在python中实现置换方法。此方法将一个列表作为输入,并返回一个元组的对象列表。

# import itertools
from itertools import permutations 

# Get all permutations of ['a', 'b', 'c'] 
perm = permutations(['a', 'b', 'c']) 

# Print the obtained permutations 
for i in list(perm): 
    print i 

假设您要获取长度为n的排列(例如n = 2),那么,您要做的就是,

#change
perm = permutations(['a', 'b', 'c']) 

#to
perm = permutations(['a', 'b', 'c'],2) 

答案 1 :(得分:0)

我认为您的代码即将完成。它只需要一点点触摸。您说随机模块包含重复项,因此它不会产生您想要的结果。为什么不使用可能的索引使用的索引的列表。这样您就可以每次生成可能的索引,并删除使用的索引。

def spec_perm(iterable, k):
    import random
    perm=[0]*len(iterable)
    used_index = [] #Initiate the list of used indexes.
    for i in range (0,len(iterable)):
        #Declare the possible range.
        if i+k < len(iterable):
            index_range = list(range(0, i+k))
        else:
            index_range = list(range(0, len(iterable)))
        #Get rid of the used indexes by using a list comprehension. 
        possible_index = [idx for idx in index_range if idx not in used_index] 
        #Make your random index choice AND assign it to a variable 
        #so that you can append it to used_index list later.
        random_index = random.choice(possible_index) 
        perm[i]=iterable[random_index]
        #Update the used indexes by appending the random index choice to the list.
        used_index.append(random_index) 


    return perm

希望这会有所帮助。 Kolay明胶:)