# CSE 143, Winter 2009, Marty Stepp # Homework 3: Stable Marriage, in Python # A Person object represents one person in the simulation along with an # ordered list of the person's preferred choices of people to marry. class Person: # Constructs a new person with the given name. # Precondition: name is not None def __init__(self, name): self.name = name self.fiancee = None # None if single self.preferences = [] # queue from most to least liked self.rankings = {} # name -> preference (1=best) # Sets this person to be engaged to the given other person. Subsequent # calls to getFiancee on this person will return other, and subsequent # calls to getFiancee on other will return this person. If either this # person or other were previously engaged, their previous engagement is # called off and the previous partner is set to be single. # # Precondition: other is not None def engage(self, other): if not self.single(): # break up self.fiancee.fiancee = None self.fiancee = other if not other.single(): # break up other.fiancee.fiancee = None other.fiancee = self # Returns True if this person has no current engagement partner # (if this person's fiancee is None) otherwise returns False. def single(self): return self.fiancee is None # Comparison function between Person objects, comparing by name. # Returns < 0 if self comes before other, > 0 if self comes after other, # or 0 if these two people have the same name. def __cmp__(self, other): return -1 if self.name < other.name else 1 if self.name > other.name else 0 # Returns a string representation of this Person that includes the # person's name and fiancee status if any, such as "Newman: single" # or "George: engaged to Charlotte (rank 1)". def __str__(self): result = self.name if self.single(): result += ": single" else: result += ": engaged to " + self.fiancee.name + \ " (rank " + str(self.rankings[self.fiancee.name]) + ")" return result