I have some code that takes an array of players. The integers in this array represent the skill level of each player. I take all the players that meet the minimum skill level, and maximum skill level, and then try to count all possible team combinations with at least a length of 3 or greater, with no single element in the array repeating in a given tuple.
What I have so far:
from itertools import combinations
def countTeams(skills, minPlayers, minLevel, maxLevel):
# Determine which skill level integers meet criteria, append to draft if valid
draft = []
for i in range(len(skills)):
if skills[i] >= minLevel and skills[i] <= maxLevel:
draft.append(skills[i])
# If no players with the skill criteria are appended, or there are not enough players to form one team, return 0
if len(draft) == 0 or len(draft) < minPlayers:
return 0
#Otherwise, if the draft list has the minimum of the number of players required to form at least one team, find all possible team combos with no repeating elements in a given tuple
elif len(draft) >= minPlayers:
combos = list(combinations(draft,minPlayers))
return len(combos)
print(countTeams([12,4,6,13,5,10],3,4,10))
This returns 4 [(4, 6, 5), (4, 6, 10), (4, 5, 10), (6, 5, 10)]
when in reality my goal is to have it returning 5 [(4, 6, 5), (4, 6, 10), (4, 5, 10), (6, 5, 10), (4,5,6,10)]
, since {4,5,6,10}
can be a team tuple possibility, because the tuple length is greater than 3 and has no repeating elements from my draft list. I know that since I use my minPlayers
integer value to determine the length of each tuple, it does not know to select tuple length values greater than or equal to 3
in this example. How can I achieve this? Would it have something to do with Math.min() or Math.max()? Is combinations() able to achieve my results, or do I need to utilize a different method? Appreciate any help, thank you!
CodePudding user response:
Below should work
Team size, N vartype: int\
combos=[]
For n in range(N, minPlayers 1,-1):
combos.append(list(combinations(draft,n)))
First line creates tuple of (4,6,6,10), then next line appends the 3-lenght tuples to combo list.
CodePudding user response:
You can use comb
from the builtin math
module instead of producing each combination explicitly and counting them. Then, just iterate over each valid team size (equal to or greater than the min).
from math import comb
def count_teams(skills, min_players, min_level, max_level):
num_skills = len([s for s in skills if min_level <= s <= max_level])
return sum(comb(num_skills, players) for players in range(min_players, num_skills))
Output:
>>> count_teams([12, 4, 6, 13, 5, 10], 3, 4, 10)
4
>>> count_teams([12, 4, 6, 13, 5, 10], 2, 6, 15)
10