Python3中嵌套循环的替代方法

时间:2020-02-09 07:21:36

标签: python nested-loops

我有一段代码可以比较学生的技能水平和作业的难度水平。它试图使学生的水平与最大可能的分配难度相匹配。我使用两个嵌套的for循环取得了成功。但是,当数量增加时,效率极低。

    def maxAssignmentPoints(self, difficulty, points, student) -> int:
        global totalPoints
        totalPoints = 0
        for i in range(len(student)):
            for j in range(len(difficulty)):
                if student[i] > difficulty[j]:
                    try:
                        if student[i] < difficulty[j + 1]:
                            totalPoints += points[j]
                    except IndexError:
                        break
                if student[i] == difficulty[j]:
                    totalPoints += points[j]
        return str(totalPoints)

我也研究过使用itertools.product,但是不确定如何比较笛卡尔积中的两个变量。 results = list(product(student, difficulty))产生(1,1)(1,2)(1,3)(2,1)...等。有什么方法可以比较这对中的值吗?

2 个答案:

答案 0 :(得分:1)

您写道:“但是,当数量增加时,效率极低。”为什么?数据越多,处理它所需的时间就越多。我认为嵌套循环对于函数的性能不是“不可思议”的问题。使用最合适的数据结构及其处理算法可以提高性能。

对于您的函数,可以用更易读的形式重写它:

def max_assignment_points(difficulties: list, points: list, students: list) -> int:
    total_points = 0
    for student in students:
        for i in range(len(difficulties) - 1):
            if difficulties[i] < student < difficulties[i + 1]:
                total_points += points[i]
            elif student == difficulties[i]:
                total_points += points[i]
    return total_points

PS

首先,在函数中使用global变量并同时更改它是一个坏主意。是什么阻止您声明局部变量?

第二,在声明一个函数时,您写道它返回一个int值,但实际上它返回了一个str

第三,使用异常退出循环似乎很奇怪。

答案 1 :(得分:1)

我认为这里没有更多的循环不好,但是高效的数据结构将派上用场。您可以在字典中保留难度范围-格式:

scores = dict(zip(difficulty, points))

现在我觉得它比以前更井井有条了。

def maxAssignmentPoints(self, students, scores) -> int:
    totalPoints = 0
    for student in range(students):
        if scores.get(student, None) is not None:
            total_points += scores[student]
    return str(totalPoints)

让我知道这是否有帮助。