LEARN COMPLEX DATA STRUCTURES Choose Your Own Adventure: Wilderness Escape

HELLO very quick problem i am having, is someone able to just explain why we need the last line in my traverse function:
‘story_node = chosen_child’
and why do we have to declare a variable story_node = self??
is it because the function will confuse it with my init function??
many thanks

 class TreeNode:
  def __init__(self, story_piece):
    self.story_piece = story_piece
    self.choices = []

  def add_child(self, node):
    self.choices.append(node)

  def traverse(self):
    story_node = self
    print(story_node.story_piece)
    while len(self.choices) > 0:
      choice = input("Enter 1 or 2 to continue the story: ")
      if choice not in ["1", "2"]:
        print("please enter a valid number!!!!!!!!! :(")
      else:
        chosen_index = int(choice)
        chosen_index -= 1
        chosen_child = story_node.choices[chosen_index]  
        print(chosen_child.story_piece)
        story_node = chosen_child
        

exercise link:
https://www.codecademy.com/paths/computer-science/tracks/complex-data-structures/modules/cspath-trees/projects/wilderness-escape

Hey!

What happens if it’s anything other than self? Have you tried seeing what printing story_node when it’s equal to self? What happens if we remove the story_node = chosen_child.

The real question you’re getting at, is how do we figure out how structures work? A simple first step for example is to draw out all the scenarios you might see as possible and write tests for them, and have print statements show you the flow of the program as it goes through different alternatives.

This is not unlike taking a car out for a spin… you want to know how it handles curves at certain speeds, hills, bad weather, etc. That way when those situations do arise, you are comfortable that you have the tools to tackle them.

1 Like

yea thats right, without the story_node = chosen_child it kept looping the first choice, so i didnt quite get what that meant, will try it with more examples.
thanks a lot