14.7.2. Demo: Navigating Trees (recursion)#

Structure of Comments & Replies#

Let’s look at our example from before of comments and replies: Initial tweet: "That last exam in sure was hard!" Two main replies, the first is "It sure was hard, what score did you get?" and that replies has two replies: "I got a 67% :(" and "I got a 73%". The second main reply is "I didn't think it was that bad". That second main reply has two replies, the first is "how was that not a super hard exam?" and the second is "of course you didn't", which has a reply "what's that supposed to mean?" which has a reply "you're an overacheiver" which has a reply "and that's bad how?"

When we want to represent Trees (like comments and replies) in code, one way of doing so is by using dictionaries.

Our initial tweet will be a dictionary with text (the comment text), and replies (a list of dictionaries).

Each of those replies will in turn be a dictioary with text (the reply text), and replies to that reply (a list of dictionaries).

And so on.

Below is code to store that in a variable (though it looks kind of messy):

comment_about_exam = {
    'text': 'That last exam in sure was hard!',
    'replies':[{
        'text': 'It sure was hard, what score did you get? ',
        'replies': [{
            'text': 'I got a 67% :(',
            'replies': []
        },{
            'text': 'I got a 73%',
            'replies': []
        }]
    }, {
        'text': 'I didn\'t think it was that bad',
        'replies': [{
            'text': 'how was that not a super hard exam?',
            'replies': []
        }, {
            'text': 'of course you didn\'t',
            'replies': [{
                'text': 'what\'s that supposed to mean?',
                'replies': [{
                    'text': 'you\'re an overacheiver',
                    'replies': [{
                        'text': 'and that\'s bad how?',
                        'replies': []
                    }]
                }]
            }]
        }]
    }]
}

We’ll also make a function that will help us display a message in a box that is indented over. Don’t worry about the details, but this uses HTML display styling, which is how websites do styling.

from IPython.display import HTML, Image, display
import html
def display_indented(text, left_margin=0):
    display(
        HTML(
            "<pre style='border:solid 1px;padding:3px;margin-left:"+ str(left_margin) + "px'>" + 
            html.escape(text) + 
            "</pre>"
        )
    )

The function above takes the text to be displayed, and optionally the left_margin for how much to indent the text box.

Below are some examples of how it works:

display_indented("Here is an example")
Here is an example
display_indented("Here is an example with an left_margin of 20", left_margin=20)
Here is an example with an left_margin of 20