I am teaching myself Python and have written a small script for exchanging Christmas gifts (this is not homework). My family likes for each person to give one gift to one person of the same gender. The following script works most of the time but sometimes fails through infinite recursion. I am not sure why, because I think the base case will eventually be met.
import random
family = {'Joe': 'm', 'Jane': 'f', 'John': 'm', 'Jill': 'f', 'James': 'm', 'Jade': 'f'}
receivers = family.copy()
givers = family.copy()
def match(giver):
index = random.randrange(len(receivers))
giverGender = givers[giver]
receiver = receivers.keys()[index]
receiverGender = receivers.values()[index]
if giver != receiver and giverGender == receiverGender:
del receivers[receiver]
return giver + ' to ' + receiver
else:
return match(giver)
# main program
for i in givers:
print match(i)
This is the error (EDIT to add full error):
Traceback (most recent call last):
File "C:\...\christmasGifts.py", line 22, in <module>
print match(i)
File "C:\...\christmasGifts.py", line 18, in match
return match(giver)
...
File "C:\...\christmasGifts.py", line 18, in match
return match(giver)
File "C:\...\christmasGifts.py", line 9, in match
index = random.randrange(len(receivers))
File "C:\Python27\lib\random.py", line 184, in randrange
istart = int(start)
RuntimeError: maximum recursion depth exceeded while calling a Python object
Thank you for any help.
First lets just consider the women. If your program runs and matches Jane to Jill, then matches Jill to Jane, Jane is the only female left and because she cannot match herself, your program runs indefinitely without a match.
Let me propose an alternate method to solve your problem. Randomly shuffle the order of your givers/recieves and have each person give a gift the the following person in the list, and have the last person in the list gift the first person. That would look something like this: