簡體   English   中英

Itertools統計所有元組長度大於等於值的組合

[英]Itertools count all combinations with tuple length being greater than or equal to value

我有一些代碼需要一組玩家。 這個數組中的整數代表每個玩家的技能水平。 我選取所有滿足最低技能水平和最高技能水平的球員,然后嘗試計算長度至少為 3 或更大的所有可能的團隊組合,數組中沒有單個元素在給定元組中重復。

到目前為止我所擁有的:

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

這將返回4 [(4, 6, 5), (4, 6, 10), (4, 5, 10), (6, 5, 10)]而實際上我的目標是讓它返回5 [(4, 6, 5), (4, 6, 10), (4, 5, 10), (6, 5, 10), (4,5,6,10)] , 因為{4,5,6,10}可能是團隊元組的可能性,因為元組長度大於 3,並且沒有來自我的草稿列表的重復元素。 我知道,因為我使用我的minPlayers整數值來確定每個元組的長度,所以它不知道在這個例子中選擇greater than or equal to 3的元組長度值。 我怎樣才能做到這一點? 它與 Math.min() 或 Math.max() 有關系嗎? combinations() 是否能夠實現我的結果,或者我是否需要使用不同的方法? 感謝任何幫助,謝謝!

下面應該工作
團隊規模,N vartype: int\

combos=[]
For n in range(N, minPlayers+1,-1):
combos.append(list(combinations(draft,n)))

第一行創建 (4,6,6,10) 的元組,然后下一行將 3 長度的元組附加到組合列表。

您可以使用內置math模塊中的comb而不是顯式生成每個組合並計算它們。 然后,只需遍歷每個有效的團隊規模(等於或大於最小值)。

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

輸出:

>>> count_teams([12, 4, 6, 13, 5, 10], 3, 4, 10)
4
>>> count_teams([12, 4, 6, 13, 5, 10], 2, 6, 15)
10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM