返回给定数组的可能排列

时间:2018-04-29 15:05:09

标签: python control-flow

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

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

  • 答案应转换为整数
  • 如果输入中存在“0”,它将产生带有前导零的字符串数字,将它们转换为整数时不予考虑。

这是我现在的代码:

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]

  

1 个答案:

答案 0 :(得分:0)

您似乎多次计算相同的排列,因为您将多次出现的数字视为不同的数字。也就是说,例如,122233122233都被计算在内,因为其中一个首先是“第一个”,而第二个则没有。

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