Skip to content

Commit 6696fa7

Browse files
committed
explanation and docs
1 parent 4cec581 commit 6696fa7

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

greedy_methods/gale_shapley_stable_matching.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,35 @@
1+
"""
2+
Gale-Shapley Stable Matching (Hospital-Proposing Version)
3+
4+
This function implements the Gale-Shapley algorithm to produce a stable
5+
matching between two groups: hospitals and students. Each hospital ranks
6+
students in order of preference, and each student ranks hospitals.
7+
8+
A matching is considered stable if there is no hospital-student pair who
9+
would both prefer to be matched with each other over their current assignment
10+
11+
Algorithm overview:
12+
1. Start with all hospitals and students unmatched.
13+
2. While there exists an unmatched hospital that still has students left
14+
to propose to:
15+
a. The hospital proposes to the highest-ranked student on its preference
16+
list that it has not yet proposed to.
17+
b. If the student is unmatched, they tentatively accept the proposal.
18+
c. If the student is already matched, they compare their current match
19+
with the new hospital and keep the one they prefer more, rejecting
20+
the other.
21+
3. Rejected hospitals continue proposing down their lists.
22+
4. The process ends when all hospitals are matched or have exhausted their
23+
preference lists.
24+
25+
Properties:
26+
- The algorithm always terminates with a stable matching.
27+
- The result is optimal for the proposing side (hospitals): each hospital
28+
receives the best student it could obtain in any stable matching.
29+
- If students propose instead, the result becomes student-optimal.
30+
"""
31+
32+
133
class GaleShapley:
234
"""Implementation of the Gale-Shapley algorithem
335
@@ -11,6 +43,7 @@ def find_matches(
1143
receivers_preferences: dict[int, list[int]],
1244
) -> dict[int, int]:
1345
"""
46+
# add some tests
1447
>>> gs = GaleShapley()
1548
>>> gs.find_matches({1: [1, 2, 3], 2: [2, 1, 3], 3: [2, 3, 1]}, {1: [1, 2, 3], 2: [2, 1, 3], 3: [2, 3, 1]})
1649
{1: 1, 2: 2, 3: 3}

0 commit comments

Comments
 (0)