Created
October 1, 2013 10:29
-
-
Save muupan/6776565 to your computer and use it in GitHub Desktop.
Gale-Shapley Algorithm for stable marriage problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Gale-Shapley Algorithm | |
""" | |
import random | |
def shuffled(lst): | |
tmp = lst[:] | |
random.shuffle(tmp) | |
return tmp | |
n = 10 | |
men = ["M" + str(i) for i in xrange(n)] | |
women = ["W" + str(i) for i in xrange(n)] | |
men_preference = {m: shuffled(women) for m in men} | |
women_preference = {w: shuffled(men) for w in women} | |
print "men_preference:" | |
print men_preference | |
print "women_preference:" | |
print women_preference | |
m_to_w = {} | |
w_to_m = {} | |
while len(m_to_w) < n: | |
man = [m for m in men if m not in m_to_w][0] | |
woman = men_preference[man][0] | |
if woman in w_to_m: | |
# Not first propose for woman | |
another_man = w_to_m[woman] | |
if women_preference[woman].index(man) < women_preference[woman].index(another_man): | |
# Win | |
del m_to_w[another_man] | |
m_to_w[man] = woman | |
w_to_m[woman] = man | |
men_preference[another_man].pop(0) | |
else: | |
# Lose | |
men_preference[man].pop(0) | |
else: | |
# First propose for woman | |
m_to_w[man] = woman | |
w_to_m[woman] = man | |
print "matching:" | |
print m_to_w |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment