首页 > 解决方案 > 内置工具,用于快速提取给定等级的元组与 [1, 2, ..., n] 上的等级相关

问题描述

我正在编写 2 个数学组合运算,我想(尽可能)多次(尽可能地)迭代,所以速度显然是至关重要的。

这是一个示例,说明我希望对任何正整数 n 和任何分级尽可能快速有效地执行操作(请参见下面的示例)。

备注:这是一个来自 Sage 数学实验的自我激励问题。非常感谢您的帮助。

示例: 让我们取 n = 6,并且集合 S = {1, 2, ..., n} = {1, 2, 3, 4, 5, 6}。有二项式(6, 2) = 15 对

[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]

以我们可以从 S 中提取的递增顺序。为了获得上述列表,我被建议使用的内置工具如下:

from itertools import combinations
n = 6
iterable = list(range(1, n+1))
r = 2
print(list(combinations(iterable, r)))

问题 0: Python 有什么更快的吗?

现在让我以从 S 到 {1, 2, 3} 的函数的形式在集合 S 上选择一个评分

分级:1、2、3 --> 1 和 4、5 --> 2 和 6 --> 3

我决定将此函数存储为字典,如下所示:

grading = {1: 1, 2: 1, 3: 1, 4: 2, 5: 2, 6: 3}

关于这个等级,我们可以计算从 S 构造的元素、对或元组的等级。

例子:

1 - 第一次建设:

我想要所有成绩等于 g0 = 4 的夫妇。这是一种明显的方法,它是在前面的代码行上天真地构建的:

g0 = 4
gradedList = []
for couple in list(combinations(iterable, 2)):
    grade = grading[couple[0]] + grading[couple[1]]
    if grade == g0:
        gradedList.append(couple)
print(gradedList)

这产生

[(1, 6), (2, 6), (3, 6), (4, 5)]

如预期的。

问题 1:是否有内置的方法来获取gradedList 和/或用 Python 最快的方法是什么?

2 - 第二次建设:

现在我想提取所有增加的 3 元组 (i, j, k),等级等于 4,并且从 i = 1 开始。

换句话说,我想要以下列表:

[(1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5)]

当然,这可以通过以下方式获得:

newIterable = list(range(2, n+1))
secondGradedList = []
for couple in list(combinations(newIterable, 2)):
    grade = grading[1] + grading[couple[0]] + grading[couple[1]]
    if grade == g0:
        secondGradedList.append((1,) + couple)
print(secondGradedList)

问题 2:是否有获取 secondGradedList 的内置方法和/或使用 Python 最快的方法是什么?

谢谢,朱利安

标签: pythonperformancecombinationsitertools

解决方案


推荐阅读