# CSE 143, Winter 2009, Marty Stepp # Homework 3: Stable Marriage, in Python # # This program runs the stable marriage simulation and prints the results. # It reads and sets up the input data for all the men and women that will # be passed in to your MatchMaker object. import re from person import * from matchmaker import * # Reads the input from the given file and puts it into the two given sets. def read_input(filename, men, women): list_to_use = men for line in file(filename): # read a person's info line = line.strip() if line.startswith("#"): continue elif (len(line) == 0): list_to_use = women else: tokens = re.split("[:,]", line) # print("tokens = " + str(tokens)); name = tokens.pop(0) person = Person(name) for partner in tokens: person.preferences.append(partner) person.rankings[partner] = len(person.preferences) list_to_use.append(person) # print("person = " + str(person)) # let's verify that the file has valid data for man in men: verify_person(man, women, men, women) for woman in women: verify_person(woman, men, men, women) # makes sure this person's data from the file is mostly valid def verify_person(person, opposite_sex, men, women): # make sure this person has some ranking for each member of opposite sex for mate in opposite_sex: if not mate.name in person.rankings: raise Exception(str(person) + " does not contain a ranking for " + \ mate.name + "\nmen : " + str(men) + "\nwomen: " + str(women)) # make sure there are not the wrong number of rankings/prefs if len(person.preferences) != len(opposite_sex): raise Exception(str(person) + " has " + str(len(person.preferences)) + \ " preferences but should have " + str(len(opposite_sex)) + \ "\nmen : " + str(men) + "\nwomen: " + str(women)) if len(person.rankings) != len(opposite_sex): raise Exception(str(person) + " has " + str(len(person.rankings)) + \ " rankings but should have " + str(len(opposite_sex)) + \ "\nmen : " + str(men) + "\nwomen: " + str(women)) # main # prompt for input file name; read data from input file print("Welcome to the CSE 143 Stable Marriage simulator!") filename = raw_input("Input file name? ") men = [] women = [] read_input(filename, men, women) # prompt for rounds rounds = int(raw_input("How many rounds (0 to repeat until stable)? ")) print("") # do match-making and print results maker = MatchMaker(men, women) while True: if (rounds == 0 and maker.stable()) or (rounds > 0 and maker.round() >= rounds): break maker.next() print("Round " + str(maker.round())) print(maker) if maker.stable(): print(str(maker.round()) + " rounds performed and stable state reached.") else: print(str(maker.round()) + " rounds performed but none were stable.")