我正在自学 Python,并编写了一个用于交换圣诞礼物的小脚本(这不是家庭作业)。我的家人喜欢每个人送一件礼物给一个同性别的人。以下脚本大部分时间都有效,但有时会因无限递归而失败。我不知道为什么,因为我认为基本情况最终会得到满足。
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)
这是错误(编辑添加完整错误):
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
感谢您的任何帮助。