我对 python 相当陌生,我已经被你们中的许多人认为是小菜一碟的挑战。输出必须是:The Monkey-child could not fall asleep, so the mother told him a story, he was once a Tiger-child The Tiger-child could not fall asleep, so the mother told him a story, he was once a Human-child The Human-child could not fall asleep, so the mother told him a story, he was once a Panther-child The Panther-child could not fall asleep, so the mother told him a story, he was once a Snake-child The Snake-child has tired and fell asleep The Panther-child has tired and fell asleep The Human-child has tired and fell asleep The Tiger-child has tired and fell asleep The Monkey-child has tired and fell asleep修改代码是以下(for和while循环是不允许的): import sys StorySequence = { "Monkey": "Tiger", "Tiger": "Human", "Panther": "Snake", "Snake": "", "Human": "Panther" } def writePaddingForDepth(depth): for i in range(0, depth): sys.stdout.write(' ') sys.stdout.flush() def endStory(thread, depth): writePaddingForDepth(depth) print ("The " + thread + "-child has tired and fell asleep.") return True def startStory(thread, depth): if (len(StorySequence[thread]) == 0): return endStory(thread, depth) writePaddingForDepth(depth) print ("The " + thread + "-child could not fall asleep, " "so the mother told him a story, he was once " + StorySequence[thread] + "-child") ## Code here startStory("Monkey", 0)我试图处理它就像它是 C 中的数组一样,但显然它不是,据我所知,它是一种dict类型,这对我来说是全新的。我想知道如何在这个例子中实现没有for或while循环的递归。
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。
添加回答
举报
0/150
提交
取消