James Toaster
James Toaster

Reputation: 27

Dict recursion without for or while loop

I'm fairly new to python, and I am already challenged by what many of you might find like a piece of cake. The output must be:

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

The code to modify is following (for and while loops are not allowed):

 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)

I tried to handle this like if it was array in C, but obviously it isn't, to all my little knowledge it is a dict type, which is something totally new for me. I would like to know how to implement recursion without for or while loops in this example.

Upvotes: 1

Views: 74

Answers (1)

J...S
J...S

Reputation: 5207

Instead of doing

for i in range(0, depth):
 sys.stdout.write('  ')

to print twice the number of spaces as depth, you could just do

sys.stdout.write('  ' * depth)

You could do something like

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)

A recursive function must have an exit condition to prevent it from being an infinite recursion.

Here, the recursion is done only as long as there's a valid key in the dictionary and the value is not an empty string.

who in StorySequence is used to check whether a key having the contents of who exists inside the dictionary StorySequence.

Upvotes: 1

Related Questions