【问题标题】:Dict recursion without for or while loop没有 for 或 while 循环的字典递归
【发布时间】:2018-12-26 21:03:08
【问题描述】:

我对 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

修改代码如下(forwhile 不允许循环):

 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 类型,这对我来说是全新的东西。我想知道在这个例子中如何在没有forwhile 循环的情况下实现递归。

【问题讨论】:

    标签: python recursion


    【解决方案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 用于检查字典StorySequence 中是否存在具有who 内容的键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-12
      • 2013-07-20
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-21
      相关资源
      最近更新 更多