1 回答

TA贡献1828条经验 获得超3个赞
而不是做
for i in range(0, depth):
sys.stdout.write(' ')
打印两倍的空格数depth,你可以这样做
sys.stdout.write(' ' * depth)
你可以做类似的事情
def fn(who, depth):
if(who in StorySequence):
if(StorySequence[who]!=''):
print ("\t" * depth + "The " + who + "-child could not fall asleep, "
"so the mother told him a story, he was once "
+ StorySequence[who] + "-child")
fn(StorySequence[who], depth+1)
print ("\t" * depth + "The " + who + "-child has tired and fell asleep.")
fn("Monkey", 0)
递归函数必须有一个退出条件,以防止它成为无限递归。
在这里,只要字典中有一个有效的键并且值不是空字符串,递归就会完成。
who in StorySequence用于检查who字典中是否存在内容为 的键StorySequence。
添加回答
举报