CodexBloom - Programming Q&A Platform

Difficulty Implementing a Stable Marriage Algorithm in Python with Custom Preferences

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-03
algorithm python gale-shapley Python

I'm trying to debug I'm collaborating on a project where I need some guidance on I'm performance testing and I'm trying to implement the Gale-Shapley stable marriage algorithm in Python, but I'm running into issues when the preference lists aren't complete for all participants... Specifically, I have a scenario where some men have ranked all women, but some women have left out a few men in their preference lists. I want to ensure the algorithm still runs correctly, but I keep getting unexpected results. Here's my implementation so far: ```python from collections import deque def stable_marriage(men, women): free_men = deque(men) proposals = {man: [] for man in men} engagements = {} while free_men: man = free_men.popleft() preferences = men[man] for woman in preferences: if woman not in engagements: engagements[woman] = man break else: current_partner = engagements[woman] if women[woman].index(man) < women[woman].index(current_partner): engagements[woman] = man free_men.append(current_partner) break proposals[man].append(woman) return engagements men = { 'A': ['X', 'Y'], 'B': ['Y', 'X'], 'C': ['X'], # C has a shorter list } women = { 'X': ['A', 'B'], 'Y': ['B', 'A'], } engagements = stable_marriage(men, women) print(engagements) ``` The scenario arises when I run this code, as I expect to see all men either engaged or free, but I get an incomplete pairing. Specifically, when I run it, I get only `{'X': 'A', 'Y': 'B'}`, which neglects that `C` isn’t engaged. I thought that by modifying the logic to check for missing preferences, it would handle the situation, but I need to seem to find the right approach. How can I adjust my implementation to accommodate situations where participants have incomplete preference lists? Are there best practices I should follow for this kind of scenario? Any insights or suggestions would be greatly appreciated! This is part of a larger CLI tool I'm building. Am I missing something obvious? I'm developing on Windows 11 with Python. What's the correct way to implement this? I'm on macOS using the latest version of Python.