-1

我想在以下条件下每周每天将 8 个任务列表中的任务随机分配给 4 个人:

  • 每个人每天正好有 2 个任务(顺序无关紧要)和
  • 不能连续 2 天以上将任务分配给同一个人(一个人第二天不能获得相同的任务)并且
  • 不能在同一天向人们分配相同的任务并且
  • 一个人一周内不能做超过 2 次相同的任务

这是我一天的代码。但是如何为一周中的 7 天编写代码,强制执行上述条件?

import random

tasks = ['task1','task2','task3','task4','task5','task6','task7','task8',]
people = ['person1', 'person2', 'person3', 'person4']

random.shuffle(tasks)

tasks = zip(*[iter(tasks)]*2)

for n,person in enumerate(people):
   print person, tasks[n]
4

1 回答 1

1

有很多方法可以解决这个问题,但一种是随机分配它们,检查它们是否符合您的规则,如果不符合则重新分配它们。

我可能会通过定义几个函数来做到这一点,您可以使用这些函数来检查任何给定的分配是否符合您的规则。

例如:

import random

def no_consecutives(allocation):
    """Check that there are no consecutive list items"""
    for i in range(1, len(allocation)):
        if allocation[i] == allocation[i-1]:
            return False
    return True

def no_more_than_twice(allocation):
    """Check that no list item appears more than twice"""
    for i in allocation:
        if allocation.count(i) > 2:
            return False
    return True

tasks = ['task1','task2','task3','task4','task5','task6','task7','task8']
people = ['person1', 'person2', 'person3', 'person4']
answer = {}
i = 0

while i < 4:
    allocations = random.choices(tasks, k=7)
    if no_consecutives(allocations) and no_more_than_twice(allocations):
        answer[people[i]] = allocations
        i += 1

print(answer)

编辑:现在我已经向您展示了如何做到这一点,并且您已经编辑了您的问题以更改条件,我会让您从这里开始。

于 2019-11-11T20:02:23.233 回答