没有 for 或 while 循环的字典递归

我对 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循环的递归。


慕的地10843
浏览 134回答 1
1回答

子衿沉夜

而不是做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。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python