Adam Crawford
Adam Crawford

Reputation: 35

Python refactoring a very manual function into a generalized function

I am working on a project that generates optimal teams. I am just going to brute force it and generate all possible combinations of people. So far I have this:

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)]

Where people is a list of ints ie [1, 2, 3, 4, 5, ... n) and teams is a list of lists which contain how large the teams should be ie [[3, 3, 5, 5], [3, 4, 4, 5]]. In both of those cases there are 3 teams being created. In the first case the first team has 3 people, the second team has 3 people the third team has 5 people, and the forth team has 5 people. Likewise in the second list, the first team has 3 people, the second team has 4 people, the third team has 4 people, and the forth team has 5 people. As you can see in my function I am doing a very manual process (wrote it to test the concept). I am wondering how I could refactor this function to accept team sizes of k ie len(teams[0]) = k.

Upvotes: 1

Views: 36

Answers (1)

folen gateis
folen gateis

Reputation: 2010

i'm not confident with my recursion skills but it works, so i think the nudge is in the good direction. just feed it with subteams like [3, 3, 5, 5] and not [[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)

Upvotes: 1

Related Questions