从名字列表中生成学生对,每周有新的学生对

时间:2018-10-21 16:24:52

标签: python python-3.x algorithm sorting

我有一个学生姓名列表,我想每周将每个学生与另一个学生配对。显然,学生每周只能成对出现,并且永远不要与以前已经有过的人一起工作。我可以使用学生姓名列表生成每个可能的配对的元组列表,但是我一直在努力获取这些配对并每周生成配对列表。

1 个答案:

答案 0 :(得分:4)

您要的是scheduling algorithm for a round robin tournament。这是用Python实现的一种方法:

def round_robin(n):
    if n % 2:
        raise ValueError("Can't pair an odd number of students")
    half = n // 2
    students = list(range(1, n + 1))
    for round in range(n - 1):
        students.append(students.pop(1))
        pairs = list(zip(students[:half], students[:half-1:-1]))
        print(pairs)

在这里起作用:

>>> round_robin(8)
[(1, 2), (3, 8), (4, 7), (5, 6)]
[(1, 3), (4, 2), (5, 8), (6, 7)]
[(1, 4), (5, 3), (6, 2), (7, 8)]
[(1, 5), (6, 4), (7, 3), (8, 2)]
[(1, 6), (7, 5), (8, 4), (2, 3)]
[(1, 7), (8, 6), (2, 5), (3, 4)]
[(1, 8), (2, 7), (3, 6), (4, 5)]