如何在python中找到一个列表中等于某个值的所有数字组合?

2024-10-02 16:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在做的这个项目就是,根据球队的比赛次数和他们的得分,找出一个赛季中所有的胜负组合。你知道吗

到目前为止,我只知道如何获得一个组合,但我不确定我将如何着手获得所有的组合。你知道吗

赢3分,平1分,输0分。

举个例子,球队打了20场比赛,得到了30分,我的结果应该是:
10-0-10
9-3-8
8-6-6
7-9-4
6-12-2
5-15-0

这就是我目前拥有的:

def process_seasons(seasons):

    # Repeating this until all seasons have been processed
    for i in range(len(seasons)):
        games = seasons[i][0]
        points = seasons[i][1]
        curSeason = i + 1
        gamesWon=gamesTied=gamesLost=0

        # default cases
        if (points % 3 == 0):
            gamesWon = points/3
            process_season(curSeason, games, points, gamesWon, gamesTied, gamesLost)
        if (points == 0):
            gamesLost = games
            process_season(curSeason, games, points, gamesWon, gamesTied, gamesLost)

        # combination cases

    pass

函数是这样调用的:

# format of list: [[season-1-games, season-1-points], [season-2-games, season-2-points], etc.]
soccer_seasons = [[1, 3], [1, 1], [1, 0], [20, 30]]
process_seasons(soccer_seasons)

Tags: 项目if次数processgamespointsseasoncases
2条回答

使用itertools.product

from itertools import product
def get_comb(games, points):
    games_list = [i for i in range(games+1)]
    return [i for i in product(games_list, games_list, games_list) 
            if i[0]*3 + i[1] == points]

>>> get_comb(20, 30)
>>> [(4, 18, 0),
     (4, 18, 1),
     (4, 18, 2), ...

因此,在本例中,第一个解决方案(多数赢=最少的游戏值点数)将非常简单地是wins = total // 3ties = total % 3losses = games - wins - ties

显然,如果我们有losses < 0,那么我们在这里失败并返回空列表。你知道吗

否则,您可以使用第一个解决方案并迭代:

wins -= 1
ties += 3
losses -= 2

在你得到wins < 0losses < 0之前,这不会改变本赛季的总积分或总比赛次数

在代码中:

def enumerate_season_records(games_played, points_earned):
  """Returns a list of tuples in the form (wins, ties, losses)"""
  wins = points_earned // 3
  ties = points_earned % 3
  losses = games_played - wins - ties
  possible_season_records = []
  while wins >= 0 and losses >= 0:
    record = (wins, ties, losses)
    possible_season_records.append(record)
    wins -= 1
    ties += 3
    losses -= 2
  return possible_season_records

请注意,这种简单的解决方案是可行的,因为点值的结果很好。一般情况是NP难的(参见:https://en.wikipedia.org/wiki/Change-making_problem

相关问题 更多 >