python - Gale-shapley算法的python实现
问题描述
我对 Gale-Shapley 算法有以下实现问题。
申请人偏好和雇主偏好具有以下形式:
applicant_prefs = ['applicant preferences', [2, 1, 3], [1, 3, 2], [1, 3, 2]]
employer_prefs = ['employer preferences', [3, 1, 2], [3, 2, 1], [2, 3, 1]]
它们是索引对应于申请人编号和雇主编号的数组。子数组的索引是工作/申请人的偏好。
因此,排名字典有字典形式:
排名有以下形式:
rankings = {'1,2': 0, '1,1': 1, '1,3': 2, '2,1': 0, '2,3': 1, '2,2': 2, '3,1': 0, '3,3': 1, '3,2': 2}
键和值的格式为:“applicant,job”:rank。我还得到了一个从 1 到 n 的空缺职位列表:
n = len(applicant_prefs) - 1
open_jobs = list(range(1, n+1)) (In this case it's 3)
当前工作是每个应聘者的匹配工作,初始化为-1,因为最初每个人都是不匹配的
current_job = [-1 for applicant in applicant_prefs]
我的任务是实现算法,这是我的尝试:
applicant = 1
while open_jobs:
#traversing through the applicants from applicant 1 to n
if(applicant <= n):
newJob = open_jobs.pop()
# if an applicant does not have a job, they accept.
if(current_job[applicant] == -1):
current_job[applicant] = newJob
else:
# if this applicant prefers the offer to their current job :
# they quit their current job and accept the offer
if(rankings[str(applicant) + "," + str(newJob)] > rankings[str(applicant) + "," + str(current_job[applicant])]):
open_jobs.append(current_job[applicant])
current_job[applicant] = newJob
else:
open_jobs.append(newJob)
applicant += 1
print(current_job)
但是,对于上面的示例,返回的数组是 [3,2,1] 而不是 [2,3,1]。我想我已经接近正确答案了。
我真的很感激任何帮助
解决方案
在 Gale--Shapely 中,雇主按照雇主喜欢的顺序向申请人提供要约。您的代码不使用雇主偏好,而是按申请人 ID 递增的顺序提供报价。
推荐阅读
- java - 加载共享库 test/libaegean.dll 时出错:没有这样的文件或目录
- mysql - 事务方法不在数据库上写入更新
- javascript - 在茉莉花测试和 TypeError 中模拟“管道”:无法读取未定义的属性“管道”
- xamarin.forms - Xamarin.Forms 如何在 App 的所有页面上添加背景图片
- swift - SwiftUI Mac OS DatePicker 在编辑时跳回一天
- php - 当会话 cookie 在 Laravel 中过期时重新加载站点
- c# - TradingView/Binance 指标的历史数据
- javascript - 追加一个字符N次的最快方法
- python - 使用 @numpy.vectorize 在 pandas 中减去 2 个 datetime64 列
- java - 有什么方法可以在 WIre Mock 中测试数组类型查询参数