![](/img/trans.png)
[英]How can I find all the possible combinations of a list of lists (in Python)?
[英]How can I find all combinations of numbers in a list that's equal to a certain value in python?
所以我正在做的这个项目是试图根据球队参加的比赛次数和他们获得的积分来找出一个赛季中所有胜利、平局和失败的组合。
到目前为止,我只知道如何获得一种组合,但我不确定如何获得所有组合。
胜一场得3分,平一场得1分,负一场得0分。
例如,球队打了 20 场比赛,得到 30 分,我的 output 应该是:
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
这就是 function 的调用方式:
# 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)
因此,在这种情况下,具体而言,第一个解决方案(最多胜利 = 最少游戏得分)将相当简单地是wins = total // 3
, ties = total % 3
, losses = games - wins - ties
显然,如果我们的losses < 0
那么我们在这里失败并返回空列表。
否则,您可以使用第一个解决方案并迭代:
wins -= 1
ties += 3
losses -= 2
这不会改变赛季的总积分或比赛的总场数,直到您获得wins < 0
或losses < 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-hard(参见: https://en.wikipedia.org/wiki/Change-making_problem )
使用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), ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.