Skip to content

Commit 15d740e

Browse files
committed
Cleaned the code a bit more, added a __str__ dunder
1 parent 3c32049 commit 15d740e

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

contents/stable_marriage_problem/code/python/stable_marriage.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,13 @@ def main():
3030
# Print preferences and the result
3131
print('Preferences of the men:')
3232
for man in men:
33-
print(f'{man.name}: {", ".join((p.name for p in man.preference))}')
33+
print(man)
3434

3535
print()
3636

3737
print('Preferences of the women:')
3838
for woman in women:
39-
print(f'{woman.name}: {", ".join((p.name for p in woman.preference))}')
39+
print(woman)
4040

4141
print('\n')
4242

@@ -75,11 +75,11 @@ def __init__(self, name):
7575
@property
7676
def next_choice(self):
7777
"""Return the next person in the own preference list"""
78-
if self.pref_index >= len(self.preference):
78+
try:
79+
return self.preference[self.pref_index]
80+
except IndexError:
7981
return None
8082

81-
return self.preference[self.pref_index]
82-
8383
def propose_to_next(self):
8484
"""Propose to the next person in the own preference list"""
8585
person = self.next_choice
@@ -130,6 +130,10 @@ def has_partner(self):
130130
"""Determine whether this person currently has a partner or not."""
131131
return self.partner is not None
132132

133+
# This allows the preferences to be printed more elegantly
134+
def __str__(self):
135+
return f'{self.name}: {", ".join(p.name for p in self.preference)}'
136+
133137

134138
if __name__ == '__main__':
135139
main()

0 commit comments

Comments
 (0)