Skip to content

Instantly share code, notes, and snippets.

@sshh12
Created March 5, 2019 23:26
Show Gist options
  • Save sshh12/57b15644c7f05e1d388b9698e0ab6058 to your computer and use it in GitHub Desktop.
Save sshh12/57b15644c7f05e1d388b9698e0ab6058 to your computer and use it in GitHub Desktop.
Take rankings from 2 csv files and use them to compute the best pairings.
from matching import Player, HospitalResident
from collections import defaultdict
import csv
def read_csv_ranks_v1(fn, other_fields=2):
users = {}
items = []
with open(fn, newline='') as csvfile:
reader = csv.reader(csvfile)
rows = [row for row in reader]
header = rows[0]
cols = len(header)
for i in range(3, cols - other_fields):
# Parse "Rank your preferences (#1 is your first preference, #10 is your least) [XXXX]"
item = header[i].split(") ")[-1][1:-1]
items.append(item)
num_items = len(items)
for row in rows[1:]:
name = row[2].split(" ")[0]
ranks = [[None, int(r)] for r in row[3:cols-other_fields]]
for i in range(num_items):
ranks[i][0] = items[i]
ranks.sort(key=lambda rank: rank[1])
users[name] = [rank[0] for rank in ranks]
return users
def read_csv_ranks_v2(fn, other_fields=2):
users = {}
rank_vals = []
with open(fn, newline='') as csvfile:
reader = csv.reader(csvfile)
rows = [row for row in reader]
header = rows[0]
cols = len(header)
for i in range(4, cols - other_fields):
# Parse "Rank your preferences (#1 is your first preference, #10 is your least) [X]"
rank = header[i].split(") ")[-1][1:-1]
rank_vals.append(int(rank))
num_ranks = len(rank_vals)
for row in rows[1:]:
name = row[2]
ranks = [(item, rank_vals[k]) for k, item in enumerate(row[4:cols-other_fields])]
ranks.sort(key=lambda rank: rank[1])
users[name] = [rank[0] for rank in ranks]
return users
def trim_rankings(a_dict, b_dict):
"""Delete values from a that dont exist in b"""
b_list = list(b_dict)
for name, prefs in a_dict.items():
a_prefs = list(prefs)
for b in a_prefs:
if b not in b_list:
prefs.remove(b)
if __name__ == "__main__":
people = read_csv_ranks_v1('People.csv')
companies = read_csv_ranks_v2('Company.csv')
trim_rankings(people, companies)
trim_rankings(companies, people)
company_sizes = {
'name': 1,
...
}
print(companies.keys())
print(people.keys())
residents = [Player(name, prefs)
for name, prefs in people.items()]
hospitals = [Player(name, prefs, capacity=company_sizes[name])
for name, prefs in companies.items()]
hr_solver = HospitalResident(suitors=residents, reviewers=hospitals)
solu = hr_solver.solve()
for comp, names in solu.items():
print('{} ({}): {}'.format(comp, company_sizes[str(comp)], str(names)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment