avatarCoucou Camille

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3927

Abstract

e provides a <code>LifoQueue</code> that works as a stack.</p> <figure id="7b94"> <div> <div>

            <iframe class="gist-iframe" src="/gist/coucou-camille/5eaf793eb1118a81c23922ffa1f1c7d7.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><h1 id="7791">Queues</h1><p id="f076">Like the third implementation of Stack, the <code>queue</code> module has a <code>Queue</code> class for the <b>first-in first-out (FIFO</b>) structure like real queues in life:</p>
    <figure id="f920">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/coucou-camille/23c7fcd54bf6254c7dc4602b242c7802.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="4ea1">As can seen from the test program, “first” is the first to be pushed to queue, and hence the first one returned when <code>pop()</code> is called.</p><h1 id="80d2">Binary Trees</h1><figure id="176f"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*w9wvlIAjade565EZiq8Hpg.png"><figcaption>Image by Author: Example of a Binary Tree</figcaption></figure><p id="858d">Trees are made of nodes: root, leaf and internal nodes. A <b>binary tree</b> is a data structure in which every node has at most two <b>child nodes</b>.</p><ul><li>Root: root the the topmost node of a tree. It can be used to access the whole tree by traversing through its child nodes and child nodes of those nodes, etc.</li></ul><p id="7f00">For example in the tree illustrated below, “STANDALONE” is the <b>root </b>node, “STAND” and “ALONE” being its<b> left and right child</b>, which also has their own <b>child nodes</b>. For “ALONE”, the only child node is the left node “O”, and “STAND” has “S” for its left and “A” for its right node. “O”, “S” and “A” nodes do not have any child node, and hence are known as <b>leaf nodes</b>.</p><p id="e0f3">A binary tree can be represented in different ways including raw data structures like <b>dictionary </b>and <b>list</b>, or <b>class representations</b> for each tree and node. There is also the <code>binarytree</code> module that can be employed straightaway.</p><p id="333e">The tree in the above image can be simply represented as a dictionary:</p><div id="1438"><pre>tree = {
<span class="hljs-string">"STANDALONE"</span>: {
    <span class="hljs-string">"ALONE"</span>: {<span class="hljs-string">"O"</span>, <span class="hljs-built_in">None</span>},
    <span class="hljs-string">"STAND"</span>: {<span class="hljs-string">"S"</span>, <span class="hljs-string">"A"</span>}
}

}</pre></div><p id="a772">Or by a list (and similarly by tuple, but the tree would become immutable):</p><div id="6bce"><pre>tree = [ <span class="hljs-string">"STANDALONE"</span>, [<span class="hljs-string">"ALONE"</span>, [<span class="hljs-string">"O"</span>, <span class="hljs-symbol">None</span>]], [<span class="hljs-string">"STAND"</span>, [<span class="hljs-string">"S"</span>, <span class="hljs-string">"A"</span>]] ]</pre></div><p id="9153">Each binary tree is represented by a list of length 3, first being the node, second being the left node, and third being the right node. Both implementations could be <b>generalized for all trees</b>.</p><p id="82c3">While class representations are possible for trees, the most straightforward and simple way is to adopt the <code>binarytree</code> module.</p><h2 id="cb0b">Trees by binarytree Module</h2><p id="5281">Python’s <code>binarytree</code> library allows generation and visualizing of binary trees. Different types of binary trees available are:</p><ul><li>Ordinary binary trees</li><li>Binary search trees (BST): left always s

Options

maller than root, and right always greater than root for all subtrees</li><li>Heap trees: max heap where root is always greater than its children, and min heap where root is always smaller than its children.</li></ul><p id="135c">For example, generate trees of the above mentioned types of depth 3:</p> <figure id="1bc1"> <div> <div>

            <iframe class="gist-iframe" src="/gist/coucou-camille/bacb8a51a42820109f2bf603ff07961b.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><h2 id="ca6c">Linked List</h2><p id="3dac">Linked lists are made of nodes, and every node has two attributes:</p><ul><li><code>data</code> : the value stored in the node</li><li><code>next</code> : reference to the next node in the list</li></ul><figure id="5924"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*-8kDWBdVPNOdSAGDksCIbw.png"><figcaption>Image by Author: Example of a Linked List</figcaption></figure><p id="3df5">A simplified class implementation of the Linked List:</p>
    <figure id="9faa">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/coucou-camille/a53cdda4e66458a6ef927786de0da19a.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="99af">Now new linked lists can be constructed as follows:</p><div id="931a"><pre><span class="hljs-comment"># first node: head in list</span>

<span class="hljs-attr">node1</span> = Node(<span class="hljs-number">1</span>) <span class="hljs-attr">linked_list</span> = LinkedList(head=node1)</pre></div><div id="4d48"><pre><span class="hljs-comment"># next 2 nodes</span> node2 = <span class="hljs-keyword">Node</span><span class="hljs-title">(2</span>) node1.set_next(node2) node3 = <span class="hljs-keyword">Node</span><span class="hljs-title">(3</span>) node2.set_next(node3)</pre></div><p id="0dc7">Additional methods could be added for the LinkedList class, such as its <b>string representation</b> and <b>iterator </b>so that it is easier to traverse through the list:</p> <figure id="79a1"> <div> <div>

            <iframe class="gist-iframe" src="/gist/coucou-camille/1881303b305c25b417e35180aa3c2437.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="2cd8"><b>Thanks for reading!</b> For more of my articles on Python &amp; Cryptos, please refer to:</p><div id="8ccf" class="link-block">
      <a href="https://readmedium.com/my-article-list-coucou-camille-c86e4e026f0c">
        <div>
          <div>
            <h2>My Article List - Constantly Updating!</h2>
            <div><h3>Python Basics &amp; Data Structures; Automation Using Python; Crypto Finance &amp; Trading…</h3></div>
            <div><p>medium.com</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/)"></div>
          </div>
        </div>
      </a>
    </div><p id="324c"><i>More content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a>. Sign up for our <a href="http://newsletter.plainenglish.io/"><b>free weekly newsletter</b></a>. Follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a><b> </b>and <a href="https://www.linkedin.com/company/inplainenglish/"><b>LinkedIn</b></a>. Check out our <a href="https://discord.gg/GtDtUAvyhW"><b>Community Discord</b></a> and join our <a href="https://inplainenglish.pallet.com/talent/welcome"><b>Talent Collective</b></a>.</i></p></article></body>

Implement Stacks, Queues, Binary Trees and Linked List in Python

Python allows users to define structures which may be readily available in other programming languages like Java.

Photo by AltumCode on Unsplash

In my previous article, I introduced the difference in features and operations time complexity of Python’s own data structures: list, tuple, set and dictionary:

And now let’s take a look at the implementations of Stack, Queue, Binary Tree and Linked List, using built-in structures, class representations or other Python library.

Stack

Stacks by List

Stack is a last-in first-out (LIFO) data structures. It works like stacking dirty plates for wash, every received dirty plate is always placed on top of the others, and for washing, the plate on top (last in) is taken out the first (first out).

Functions associated with stacks are:

  • empty() : to check whether the stack is empty
  • size() : returns number of elements in stack
  • push() : add new element to the top of stack
  • peek() : returns the element on top of the stack
  • pop() : removes and returns the element on top of the stack

Basic features for stacks: orders matter, duplicates are allowed, and the structure needs to be mutable (for addition and deletion of elements). Hence list is perfect for the implementation:

The implementation by list, although convenient, has its shortcomings. The most significant issue is that the time complexity of list appending has a time complexity of O(n) while for stack it should be O(1). Hence the implementation above could have performance issue as the size increases.

Stacks by Deque

The deque class from Python’s collections module is preferred as it allows an O(1) time complexity for appending:

The program returns the same result when applied to the same block of test codes as illustrated in the previous section.

Stacks by LifoQueue

Python’s queue module provides a LifoQueue that works as a stack.

Queues

Like the third implementation of Stack, the queue module has a Queue class for the first-in first-out (FIFO) structure like real queues in life:

As can seen from the test program, “first” is the first to be pushed to queue, and hence the first one returned when pop() is called.

Binary Trees

Image by Author: Example of a Binary Tree

Trees are made of nodes: root, leaf and internal nodes. A binary tree is a data structure in which every node has at most two child nodes.

  • Root: root the the topmost node of a tree. It can be used to access the whole tree by traversing through its child nodes and child nodes of those nodes, etc.

For example in the tree illustrated below, “STANDALONE” is the root node, “STAND” and “ALONE” being its left and right child, which also has their own child nodes. For “ALONE”, the only child node is the left node “O”, and “STAND” has “S” for its left and “A” for its right node. “O”, “S” and “A” nodes do not have any child node, and hence are known as leaf nodes.

A binary tree can be represented in different ways including raw data structures like dictionary and list, or class representations for each tree and node. There is also the binarytree module that can be employed straightaway.

The tree in the above image can be simply represented as a dictionary:

tree = {
    "STANDALONE": {
        "ALONE": {"O", None},
        "STAND": {"S", "A"}
    }
}

Or by a list (and similarly by tuple, but the tree would become immutable):

tree = [
    "STANDALONE",
    ["ALONE", ["O", None]],
    ["STAND", ["S", "A"]]
]

Each binary tree is represented by a list of length 3, first being the node, second being the left node, and third being the right node. Both implementations could be generalized for all trees.

While class representations are possible for trees, the most straightforward and simple way is to adopt the binarytree module.

Trees by binarytree Module

Python’s binarytree library allows generation and visualizing of binary trees. Different types of binary trees available are:

  • Ordinary binary trees
  • Binary search trees (BST): left always smaller than root, and right always greater than root for all subtrees
  • Heap trees: max heap where root is always greater than its children, and min heap where root is always smaller than its children.

For example, generate trees of the above mentioned types of depth 3:

Linked List

Linked lists are made of nodes, and every node has two attributes:

  • data : the value stored in the node
  • next : reference to the next node in the list
Image by Author: Example of a Linked List

A simplified class implementation of the Linked List:

Now new linked lists can be constructed as follows:

# first node: head in list
node1 = Node(1)
linked_list = LinkedList(head=node1)
# next 2 nodes
node2 = Node(2)
node1.set_next(node2)
node3 = Node(3)
node2.set_next(node3)

Additional methods could be added for the LinkedList class, such as its string representation and iterator so that it is easier to traverse through the list:

Thanks for reading! For more of my articles on Python & Cryptos, please refer to:

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Check out our Community Discord and join our Talent Collective.

Python
Data Structures
Recommended from ReadMedium