|
|
这题用个二位数组就可以了吧。 大家觉得这个方案可行的话,求个大米- data = {
- 'a': ['c', 'd'],
- 'b': ['d', 'a', 'c'],
- 'c': ['a', 'b'],
- 'd': ['c', 'a', 'b']
- }
- userMapping={
- "a":0,
- "b":1,
- "c":2,
- "d":3
- }
- reverseUserMapping=[user for user in userMapping.keys()]
- numOfPlayer=len(data)
- metric=[[None]*numOfPlayer for i in range(0, numOfPlayer)]
- for k,preferences in data.items():
- row_num=userMapping.get(k)
- counter=0
- for p in preferences:
- col_num=userMapping.get(p)
- metric[row_num][col_num]=counter
- counter+=1
- print(metric)
- def has_mutual_first_choice(user):
- user_id=userMapping.get(user)
- first_choice=metric[user_id].index(0)
- if metric[first_choice].index(0)==user_id:
- return True
- return False
- # print(has_mutual_first_choice('a')) # true
- # print(has_mutual_first_choice('b')) # false
- def has_mutual_pair_for_rank(user, rank):
- user_id=userMapping.get(user)
-
- first_choice=metric[user_id].index(rank)
- if rank in metric[first_choice] and metric[first_choice].index(rank)==user_id:
- return True
- return False
- # print(has_mutual_pair_for_rank('a', 0)) # true (a and c)
- # print(has_mutual_pair_for_rank('b', 1)) # true (a and d are mutually each others'print()
- def changed_pairings(user, rank):
- user_id=userMapping.get(user)
- upgraded_user=metric[user_id].index(rank)
- downgrad_user=metric[user_id].index(rank-1)
- is_upgraded_user_mutual_before=has_mutual_pair_for_rank(user, rank)
- is_downgrad_user_mutual_before=has_mutual_pair_for_rank(user, rank-1)
-
- metric[user_id][upgraded_user]=rank-1
- metric[user_id][downgrad_user]=rank
-
- is_upgraded_user_mutual_after=has_mutual_pair_for_rank(user, rank-1)
- is_downgrad_user_mutual_after=has_mutual_pair_for_rank(user, rank)
- result=set()
- if is_upgraded_user_mutual_before != is_upgraded_user_mutual_after:
- result.add(reverseUserMapping[upgraded_user])
- if is_downgrad_user_mutual_before != is_downgrad_user_mutual_after:
- result.add(reverseUserMapping[downgrad_user])
- metric[user_id][upgraded_user]=rank
- metric[user_id][downgrad_user]=rank-1
- return list(result)
-
-
-
- print(changed_pairings('d', 1) )
- # ['a']
- # if b's third choice becomes their second choice, c and b will become a mutually ranked pair (mutual second-choices)
- print(changed_pairings('b', 2))
- # returns ['c']
- # if b's second choice becomes their first choice, no mutually-ranked pairings are affected
- print(changed_pairings('b', 1))
- # returns []
复制代码 |
|