首页 > 解决方案 > 返回给定数组的可能排列

问题描述

对于带有字符串数字的给定列表,我想返回可以使用列表中的所有元素生成的不同字符串数字(因此,如果有 5 个元素,则该数字应由 5 位数字组成)。

任务是返回列表中可能的排列、最小排列和最大排列。

这是我现在的代码:

from itertools import permutations

def proc_arr(arr):


    lst = [] # define new list
    list_of_tuples = list(permutations(arr, len(arr))) # now they are tuples in a list

    # convert to integers in list
    separator = [map(str,x) for x in list_of_tuples]
    together = [int(''.join(s)) for s in separator]

    # append to new list and return the len of possible combinations, min and max value
    lst.append(len(together))
    lst.append(min(together))
    lst.append(max(together))

    #print(lst)
    return lst


proc_arr(['1','2','2','3','2','3'])

但是,我不明白为什么我没有得到正确数量的排列。

输入:proc_arr(['1', '2', '2', '3', '2', '3']) 输出:[60, 122233, 332221]

我得到 [720, 122233, 332221]

输入输出的另一个例子

输入:proc_arr(['1','2','3','0','5','1','1','3']) 输出:[3360, 1112335, 53321110]

标签: pythoncontrol-flow

解决方案


您似乎多次计算相同的排列,因为您将多次出现的数字视为不同的。也就是说,例如,122233并且122233每个都被计算在内,因为一个具有“第一个”3,而第二个没有。

一种解决方案是计算您将拥有多少重复项并将它们从您的计数中消除。在您的示例中,有 3 个2s,因此可以以 1*2*3=6 种方式排列它们,同时保持其他所有内容不变;因此,由于 2,您的答案大了 6 倍。同样对于 2 3s:1*2=2 方式,因此将您的答案除以 2。这将使您得到 720/6/2 = 60,即正确答案。


推荐阅读