小编kak*_*car的帖子

获取具有不同部分的整数分区数的有效算法(分区函数 Q)

我需要创建一个函数,该函数将采用一个参数int和输出int,该输出表示输入整数分区的不同部分的数量。即,

input:3 -> output: 1 -> {1, 2}
input:6 -> output: 3 -> {1, 2, 3}, {2, 4}, {1, 5}
...
Run Code Online (Sandbox Code Playgroud)

因为我只寻找不同的部分,所以不允许这样的事情:

4 -> {1, 1, 1, 1} or {1, 1, 2}

到目前为止,我已经设法提出了一些算法,可以找到所有可能的组合,但它们非常缓慢且仅在此之前有效n=100。而且因为我只需要组合的数量而不是组合本身,所以分区函数 Q应该可以解决问题。有人知道如何有效地实施吗?

有关问题的更多信息:OEIS , Partition Function Q

编辑:

为避免混淆,DarrylG答案还包括琐碎(单个)分区,但这不会以任何方式影响其质量。

编辑 2:(jodag接受的答案)不包括琐碎的分区。

python algorithm partitioning

6
推荐指数
2
解决办法
1570
查看次数

在列表字典中找到最大列表范围的更好(更整洁)方法是什么

我有包含列表作为值的字典。Listlen(2)表示数组的范围:

new_dict = {0: [0, 7], 1:[15, 21], 2:[-5, 3]}

我需要找到具有最大范围即最大的列表的键 list[1] - list[0]

我已经这样做了,它工作正常,但我假设它可以以更简单或更pythonic的方式完成。

largest = float("-inf")
largest_list = []
for key in new_dict.keys():
        temp = new_dict[key][1] - new_dict[key][0]
        if temp > largest:
            largest = temp
            largest_list = new_dict[key]
Run Code Online (Sandbox Code Playgroud)

python dictionary list

2
推荐指数
1
解决办法
101
查看次数

检查项目是否在列表列表中

我正在查看项目是否在列表列表中。

List1 = [['a','b','c'],['d','e','f'],['g','h','i']]
Run Code Online (Sandbox Code Playgroud)

如果b在列表中的任何列表中,则打印True。否则,打印False

这样做的pythonic方法是什么?

python

1
推荐指数
1
解决办法
121
查看次数

标签 统计

python ×3

algorithm ×1

dictionary ×1

list ×1

partitioning ×1