Python将一个非常手动的函数重构为一个通用函数



我正在从事一个能够产生最佳团队的项目。我只是要用暴力来制造所有可能的人的组合。到目前为止,我有这个:

from itertools import combinations
def testing(people, people_copy, teams):
for team in teams:
people_copy = people.copy()
for comb in list(combinations(people_copy, team[0])):
people_copy = people.copy()
for i in comb:
people_copy.remove(i)
for combi in list(combinations(people_copy, team[1])):
people_copy = people.copy()
for i in comb:
people_copy.remove(i)
for j in combi:
people_copy.remove(j)
for combin in list(combinations(people_copy, team[2])):
people_copy = people.copy()
for i in comb:
people_copy.remove(i)
for j in combi:
people_copy.remove(j)
for k in combin:
people_copy.remove(k)
for combina in list(combinations(people_copy, team[3])):
yield [list(comb), list(combi), list(combin), list(combina)]

其中people是int列表(即[1,2,3,4,5,…n(,teams是包含团队规模的列表(即[3,3,5,5],[3,4,4,5]](。在这两种情况下,都会创建3个团队。在第一种情况下,第一队有3人,第二队有3个人,第三队有5个人,第四队有5人。同样在第二个名单中,第一队有3人,第二队有4人,第三队有4个人,第四队有5个人。正如你在我的函数中看到的,我正在做一个非常手动的过程(编写它是为了测试概念(。我想知道如何重构这个函数以接受k ie len(teams[0](=k的团队规模。

我对自己的递归技能没有信心,但它很有效,所以我认为推动是朝着好的方向发展的。只需给它提供像[3, 3, 5, 5]而不是[[3, 3, 5, 5], [3, 4, 4, 5]]这样的子程序

def testing(people, teams, result=[]):
if not teams:
yield result
return
new_team=teams.copy()
team=new_team.pop(0)
people_team=people.copy()
for comb in combinations(people, team):
people_comb=people_team.copy()
for val in comb:
people_comb.remove(val)
new_result=result.copy()
new_result.append(comb)
yield from testing(people_comb, new_team, new_result)

最新更新