生成数值排列(迭代与递归)

时间:2020-10-29 15:57:08

标签: python iteration permutation numeric

我想我正在尝试做一些非常基础和非常简单的事情。因此,我确定Stack Overflow已经有关于此任务的文章,但我想不是吗?也许这是一个无关紧要的概念?抱歉,如果已经有相关的帖子。我找不到。

这是我要完成的工作:给定列表长度 n 和最大元素值 m ,生成列表的所有排列,每个元素之间0和 m

问题:1.是否可以递归地执行此操作? 2.对于此概念,递归是最佳的(在计算资源,时间等方面)还是迭代更好? 3.是否有更好的方法(较不复杂)使用迭代来实现此目的(请参见下面的代码)?

下面有更多信息

我已经编辑了代码和两个示例,以产生并展示完整的解决方案

这里有两个例子:

示例1:n = 3,m = 2 输出:

[0, 0, 0]
[0, 0, 1]
[0, 0, 2]
[0, 1, 0]
[0, 1, 1]
[0, 1, 2]
[0, 2, 0]
[0, 2, 1]
[0, 2, 2]
[1, 0, 0]
[1, 0, 1]
[1, 0, 2]
[1, 1, 0]
[1, 1, 1]
[1, 1, 2]
[1, 2, 0]
[1, 2, 1]
[1, 2, 2]
[2, 0, 0]
[2, 0, 1]
[2, 0, 2]
[2, 1, 0]
[2, 1, 1]
[2, 1, 2]
[2, 2, 0]
[2, 2, 1]
[2, 2, 2]

示例1:n = 2,m = 4 输出:

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

我的直觉告诉我,这可以递归完成,但是我不知道该怎么做(我是初学者)。目前,我有一个解决方案可以反复实现此目的:

def permute(curr_permute,max_num,reset_flgs,reset_ind):
    '''
    Increment Logic Structure
    '''
    perm_ind = 0
    max_val_flgs = [0]*len(curr_permute)
    for c_i in range(len(curr_permute)):
        if ((curr_permute[c_i] == max_num) and (c_i < (len(curr_permute)-1))):
            if ((reset_ind == c_i) and (reset_flgs[c_i] == 1)):
                reset_ind += 1
                reset_flgs[c_i] = 0
                max_val_flgs[c_i] = 1
                continue
            else:
                perm_ind += 1
                max_val_flgs[c_i] = 1
        elif (c_i == (len(curr_permute)-1)):
            if (curr_permute[c_i] == max_num):
                perm_ind = c_i
                max_val_flgs[c_i] = 1
            else:
                perm_ind = c_i
        elif (curr_permute[c_i] < max_num):
            perm_ind += 1
    '''
    Reverse the lists
    '''
    max_val_flgs.reverse()
    curr_permute.reverse()
    reset_flgs.reverse()
    '''
    Reset Logic Structure
    '''
    for n_i in range(len(curr_permute)):
        if (max_val_flgs[n_i] == 0):
            break
        elif ((max_val_flgs[n_i] == 1) and (reset_flgs[n_i] == 1)):
            curr_permute[n_i] = 0
            perm_ind += -1
    '''
    Reverse the lists
    '''
    curr_permute.reverse()
    reset_flgs.reverse()
    '''
    Apply the permutation increment
    '''
    curr_permute[perm_ind] += 1
    return(curr_permute,reset_flgs,reset_ind)

def Permutation_Generation():
    n = 2
    m = 4
   
    curr_permute = [0]*n
    reset_flgs = [1]*n
    reset_ind = 0
    All_Permutations = [list(curr_permute)]
    while (sum(curr_permute) < (n*m)):
        print(curr_permute)
        [curr_permute,reset_flgs,reset_ind] = permute(curr_permute,m,reset_flgs,reset_ind)
        All_Permutations.append(list(curr_permute))
    print(curr_permute)
    return(All_Permutations)

为垃圾代码道歉。一旦我想出一种成功完成此操作的方法,便无需花费很多精力进行清理或提高效率。我的猜测是,对于我要解决的概念,这段代码太复杂了。

3 个答案:

答案 0 :(得分:0)

3。。您想获取所有排列。给定n和m的排列数为(m + 1)^ n。 因为您实际上要打印所有这些文件,所以时间复杂度也是O((m + 1)^ n),这是您反复进行打印时得到的结果。

1 + 2。。我认为您不应该使用递归来做到这一点,O((m + 1)^ n)是您可以做到的最佳时间,这就是您得到的使用迭代时。递归也会因为它的内存堆栈而占用更多的内存。

答案 1 :(得分:0)

这个问题似乎已经解决了,但是我想为迭代排列提供一个替代方案,这个方法要简单一些。在这里,我使用列表推导,格式化的字符串文字(f'string'字符串)和eval内置方法。希望这种观点对您有所帮助(以某种方式?)。

def get_permutations_list(array_size, max_value):
    '''Returns a list of arrays that represent all permutations between zero
    and max_value'''

    array_member =''
    for_loops=''

    #Does a loop iteration for each member of the permutation list template
    for i in range(array_size):

        #adds a new member in each permutation
        array_member += f'x{i}, '

        #adds a new corresponding for loop
        for_loops+=" for x{i} in range({value})".format(i=i, 
                                                   value=max_value)

    output = f'[[{array_member}] {for_loops}]' #combines it all together
    return eval(output)

a = get_permutations_list(array_size=2, max_value=2)
print(a)
#Result: [[0,0],[0,1],[1,0],[1,1]]

答案 2 :(得分:0)

我认为n和m的输出分别不是3、2确实有意义。在第六行[0, 2, 0]之后,是否应该紧跟[0, 2, 1]而不是[1, 0, 0]?在第13行之后也发生了同样的情况。

无论如何,这是一个递归替代项:

n = 3
m = 2

def permutation(n, m):
    if n <= 0:
        yield []
    else:
        for i in range(m+1):
            for j in permutation(n-1, m):
                yield [i] + j

# or even shorter
def permutation(n, m):
    return [[i] + j for i in range(m + 1) for j in permutation(n - 1, m)] if n > 0 else []


for i in permutation(n, m):
    print(i)

输出:

[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], ..., [2, 1, 0], [2, 1, 1], [2, 1, 2], [2, 2, 0], [2, 2, 1], [2, 2, 2]]
相关问题