朋友遇到一个面试题,让我帮忙实现,题目如下:
红队有A1,B1,C1三名队员,蓝队有A2,B2,C2三名队员,每轮比赛各队出一名队员参加,一名队员只能参加一次比赛,假设A1不会和B2打,B1不会和B2和C2打,那么可能出现的组合情况是什么?
这个面试题的难点在于如何算出所有可能的组合,考虑扩展性的话,还得考虑两队人数不相同的问题,因此有了下面代码:
# coding: utf-8import copydef 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_listdef 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()
显示效果为:
肯能组合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'}]
通过递归方式来解决
===================================================
其实啥都是虚的,你们都是来看妹子的,是不是!!!