编程语言
首页 > 编程语言> > 为什么这个Python脚本偶尔会递归?

为什么这个Python脚本偶尔会递归?

作者:互联网

我正在教自己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

感谢您的任何帮助.

解决方法:

首先让我们考虑一下女性.如果您的程序运行并且将Jane与Jill匹配,那么将Jill与Jane匹配,Jane是唯一的女性,因为她无法匹配自己,您的程序无限期地运行而没有匹配.

让我提出另一种方法来解决您的问题.随机地改变你的送礼者/收据的顺序,并让每个人在列表中给下面的人送礼物,并让列表中的最后一个人送给第一个人.这看起来像这样:

from random import shuffle
women = ['Jane', 'Jill', 'Jade']
shuffle(women)
print women[-1] + ' to ' + women[0]
for i in range(len(women) - 1):
    print women[i] + ' to ' + women[i+1]

标签:python,infinite-loop
来源: https://codeday.me/bug/20190725/1536676.html