朋友遇到一個面試題,讓我幫忙實現,題目以下:面試
紅隊有A1,B1,C1三名隊員,藍隊有A2,B2,C2三名隊員,每輪比賽各隊出一名隊員參加,一名隊員只能參加一次比賽,假設A1不會和B2打,B1不會和B2和C2打,那麼可能出現的組合狀況是什麼?app
這個面試題的難點在於如何算出全部可能的組合,考慮擴展性的話,還得考慮兩隊人數不相同的問題,所以有了下面代碼:spa
# coding: utf-8 import copy def get_team_group_list(team1, team2): if len(team1) == 1 or len(team2) == 1: team_group_list = list() for user1 in team1: for user2 in team2: user_group = { "U1": user1, "U2": user2 } user_group_list = [user_group] team_group_list.append(user_group_list) return team_group_list else: sub_team1 = team1[1:] user1 = team1[0] team_group_list = list() for user2 in team2: sub_team2 = filter(lambda x: x != user2, team2) sub_team_group_list = get_team_group_list(sub_team1, sub_team2) for user_group_list in sub_team_group_list: tmp_user_group_list = copy.deepcopy(user_group_list) user_group = { "U1": user1, "U2": user2 } tmp_user_group_list.append(user_group) team_group_list.append(tmp_user_group_list) return team_group_list def test(): team1 = ["A1", "B1", "C1"] team2 = ["A2", "B2", "C2"] exclude_condition_list = [ { "U1": "A1", "U2": "B2" }, { "U1": "B1", "U2": "B2" }, { "U1": "B1", "U2": "C2" } ] team_group_list = get_team_group_list(team1, team2) for num in range(0, len(team_group_list)): print("肯能組合{0}:".format(num)) print(team_group_list[num]) for num in range(0, len(team_group_list)): is_valid = True team_group = team_group_list[num] for exclude_condition in exclude_condition_list: match_list = filter(lambda user_group: ( user_group["U1"] == exclude_condition["U1"] and user_group["U2"] == exclude_condition["U2"] ), team_group) if len(match_list) > 0: is_valid = False if is_valid: print("組合{0}知足條件:".format(num)) print(team_group_list[num]) test()
顯示效果爲:code
肯能組合0: [{'U1': 'C1', 'U2': 'C2'}, {'U1': 'B1', 'U2': 'B2'}, {'U1': 'A1', 'U2': 'A2'}] 肯能組合1: [{'U1': 'C1', 'U2': 'B2'}, {'U1': 'B1', 'U2': 'C2'}, {'U1': 'A1', 'U2': 'A2'}] 肯能組合2: [{'U1': 'C1', 'U2': 'C2'}, {'U1': 'B1', 'U2': 'A2'}, {'U1': 'A1', 'U2': 'B2'}] 肯能組合3: [{'U1': 'C1', 'U2': 'A2'}, {'U1': 'B1', 'U2': 'C2'}, {'U1': 'A1', 'U2': 'B2'}] 肯能組合4: [{'U1': 'C1', 'U2': 'B2'}, {'U1': 'B1', 'U2': 'A2'}, {'U1': 'A1', 'U2': 'C2'}] 肯能組合5: [{'U1': 'C1', 'U2': 'A2'}, {'U1': 'B1', 'U2': 'B2'}, {'U1': 'A1', 'U2': 'C2'}] 組合4 知足條件: [{'U1': 'C1', 'U2': 'B2'}, {'U1': 'B1', 'U2': 'A2'}, {'U1': 'A1', 'U2': 'C2'}]
經過遞歸方式來解決orm
===================================================blog
其實啥都是虛的,大家都是來看妹子的,是否是!!!遞歸