python - 返回给定数组的可能排列
问题描述
对于带有字符串数字的给定列表,我想返回可以使用列表中的所有元素生成的不同字符串数字(因此,如果有 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]
解决方案
您似乎多次计算相同的排列,因为您将多次出现的数字视为不同的。也就是说,例如,122233
并且122233
每个都被计算在内,因为一个具有“第一个”3,而第二个没有。
一种解决方案是计算您将拥有多少重复项并将它们从您的计数中消除。在您的示例中,有 3 个2
s,因此可以以 1*2*3=6 种方式排列它们,同时保持其他所有内容不变;因此,由于 2,您的答案大了 6 倍。同样对于 2 3
s:1*2=2 方式,因此将您的答案除以 2。这将使您得到 720/6/2 = 60,即正确答案。
推荐阅读
- c - 用 C 设置 ROS Melodic
- javascript - 需要帮助编码夜间模式 wordpress webiste,它将根据晚上 7 点到早上 7 点自动触发(如 instagram),但对于我的网站
- flutter - 有没有办法在 Flutter 中控制系统音乐?
- oracle - Oracle ATP 钱包连接
- c# - Blazor WebAssembly - trackBy 等效
- caching - 当项目版本不同时,Infinispan 支持复制缓存
- python - 将抓取的数据转换为字典
- java - 使用堆算法生成排列时出错
- python - 无法从获得的输出中创建数据框
- r - 在 R 中的间隙箱线图的上部添加 Y 刻度