Expressing Nodes in Python

This trippy graphic brought to you by the Medium article “Visualizing Graphs in 3D with WebGL.”

This trippy graphic brought to you by the Medium article “Visualizing Graphs in 3D with WebGL.”

This requires some knowledge with object-oriented programming in Python, which is a method that allows for structuring programs so that each property and behavior can be bundled into a single object. It’s pretty useful—check it out here. I’ll make a writeup on it soon.

A node in computer science is defined as a basic unit of a data structure. Many situations can be described with nodes:

Let’s kick off with the basics and define our Node object

class Node:
    def __init__(self, id=None):
        self.id = id
        self.nextNode = None

That’s pretty much the most basic form of a node we need to define. Now here’s how we implement this.

n1 = Node("A")
n2 = Node("B")
n3 = Node("C")

We instantiate three nodes: “A”, “B”, and “C”. These strings are passed in as each respective node’s identification (we can pass in anything else, but for simplicity’s sake let’s stick to strings for now).

Let’s say we want to describe this (directed) graph:

node_image_1.png

Here’s how we describe that.

n1.nextNode = n2
n2.nextNode = n3

Great! We’re done. But how can we verify that these nodes are connected?

We’ll need to transverse through the graph. We first define a starting node.

currentNode = n1

Great! Next, we transverse. While we are on a node, we are going to print the node ID and move on to the next node.

while currentNode:
    print(currentNode.id)
    currentNode = currentNode.nextNode

Done! When we run this, we should get the following output:

[OUT]:
A
B
C

Since we defined the default value of self.nextNode to be None, when we arrived at node C there were no more nodes available for us to move to. This is called a leaf node because, like a leaf, we have reached the end of that traversal. Thus, we broke out of the while loop.

Let’s try one more graph.

node_image_2.png

If you’ve been following through, you only need one more line to describe this.

n3.nextNode = n1

Let’s transverse through this. Remember, we need to set our starting node again.

currentNode = n1
while currentNode:
    print(currentNode.id)
    currentNode = currentNode.nextNode

[OUT]:
A
B
C
A
B
C
A
B
C
A
B
C
.
.
.

Ohhh nooooo you broke it. Just kidding. It’s supposed to loop indefinitely. If you did this in terminal, then break out of that loop by pressing CTRL + C.

There you have it—your (barely of an) intro to expressing and implementing nodes in Python.

The COVID-19 Pandemic Hackathon

Making a Just Dance Unlimited song randomizer