<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[theroyakash publications]]></title><description><![CDATA[Computer scientist theroyakash researches high performance algorithms and distributed systems. This is the publication from theroyakash.]]></description><link>https://publications.theroyakash.com</link><generator>RSS for Node</generator><lastBuildDate>Mon, 07 Sep 2026 21:31:23 GMT</lastBuildDate><atom:link href="https://publications.theroyakash.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to use graph as a data structure in C++]]></title><description><![CDATA[Graph Usage
Graph is one of the most common and important data structure. With C++ and STL I'll show you the best possible implementation for graph that you'll be able to implement and analyze in your code at FAANG interviews within the time constrai...]]></description><link>https://publications.theroyakash.com/graph-in-cpp</link><guid isPermaLink="true">https://publications.theroyakash.com/graph-in-cpp</guid><category><![CDATA[algorithms]]></category><category><![CDATA[C++]]></category><category><![CDATA[data structures]]></category><category><![CDATA[Computer Science]]></category><category><![CDATA[Competitive programming]]></category><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Mon, 11 Apr 2022 12:04:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649678292233/sV0zvxlfD.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-graph-usage">Graph Usage</h1>
<p>Graph is one of the most common and important data structure. With C++ and STL I'll show you the best possible implementation for graph that you'll be able to implement and analyze in your code at FAANG interviews within the time constraints.</p>
<h2 id="heading-graph-adjacency-list-vs-adjacency-matrix">Graph Adjacency List vs Adjacency Matrix</h2>
<p>Most of the cases the List representation is good enough, if the graph is sparse then it will take less space, and if the graph is dense you should use the adjacency matrix representation.</p>
<p>In my opinion any graph with <strong>less than 70% of the all possible edges</strong>: \(\text{Count(E)} \geq 0.7 * {n \choose 2}\) present can be considered to be implemented as adjacency list.</p>
<h2 id="heading-c-graph-representation">C++ Graph representation</h2>
<p>APIs to implement
<strong>Graph Class</strong></p>
<ul>
<li>internal hashtable for the adjacency list representation</li>
<li>all the edges in a vector, in order to quickly see what are the edges are there?</li>
<li>function to add edge and a function to add vertices into the graph class.</li>
</ul>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;list&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;unordered_map&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;vector&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;utility&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>;

<span class="hljs-comment">// Directed graph implementation</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Graph</span>{</span> 
<span class="hljs-keyword">private</span>:
    <span class="hljs-built_in">unordered_map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-built_in">list</span>&lt;<span class="hljs-built_in">pair</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt;&gt;&gt; adj_list;
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">pair</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">char</span>&gt;&gt; E; <span class="hljs-comment">// edge set</span>
<span class="hljs-keyword">public</span>:
    <span class="hljs-function"><span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">pair</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">char</span>&gt;&gt; <span class="hljs-title">edges</span><span class="hljs-params">()</span></span>{
        <span class="hljs-keyword">return</span> E;
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">add_edge</span><span class="hljs-params">(<span class="hljs-keyword">char</span> vertex1, <span class="hljs-keyword">char</span> vertex2, <span class="hljs-keyword">int</span> weight)</span></span>{
        adj_list[vertex1].push_front(<span class="hljs-built_in">make_pair</span>(
            vertex2, weight
        ));

        E.push_back({vertex1, vertex2});
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">register_vertex</span><span class="hljs-params">(<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">char</span>&gt; vertices)</span></span>{
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> v:vertices){
            <span class="hljs-built_in">list</span>&lt;<span class="hljs-built_in">pair</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt;&gt; l;
            adj_list.insert({v, l});
        }
    }

    <span class="hljs-function"><span class="hljs-built_in">unordered_map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-built_in">list</span>&lt;<span class="hljs-built_in">pair</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt;&gt;&gt; <span class="hljs-title">view</span><span class="hljs-params">()</span></span>{
        <span class="hljs-keyword">return</span> adj_list;
    }
};
</code></pre>
<p>The following code shows how to make a graph and use it</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    Graph g;
    <span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">char</span>&gt; v = {<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>};
    g.register_vertex(v);
    g.add_edge(<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>, <span class="hljs-number">32</span>);
    g.add_edge(<span class="hljs-string">'a'</span>, <span class="hljs-string">'d'</span>, <span class="hljs-number">2</span>);
    g.add_edge(<span class="hljs-string">'b'</span>, <span class="hljs-string">'d'</span>, <span class="hljs-number">12</span>);
    g.add_edge(<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>, <span class="hljs-number">98</span>);
    g.add_edge(<span class="hljs-string">'c'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-number">1</span>);

    <span class="hljs-built_in">unordered_map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-built_in">list</span>&lt;<span class="hljs-built_in">pair</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt;&gt;&gt; <span class="hljs-built_in">map</span> = g.view();

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> data:<span class="hljs-built_in">map</span>){
        <span class="hljs-built_in">cout</span> &lt;&lt; data.first &lt;&lt; <span class="hljs-string">" "</span>;

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> neighbor:data.second)
            <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"["</span> &lt;&lt; neighbor.first &lt;&lt; <span class="hljs-string">": "</span> &lt;&lt; neighbor.second &lt;&lt; <span class="hljs-string">"]"</span>;

        <span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"\n"</span>;
    }

    <span class="hljs-comment">// print all the edges</span>
    <span class="hljs-keyword">auto</span> edges = g.edges();
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> edge:edges){
        <span class="hljs-built_in">cout</span> &lt;&lt; edge.first &lt;&lt; <span class="hljs-string">"-&gt;"</span> &lt;&lt; edge.second &lt;&lt; <span class="hljs-string">"\n"</span>;

    }
}
</code></pre>
<p>If you wish to get all the contents in your email please subscribe below.</p>
]]></content:encoded></item><item><title><![CDATA[Pre order, In order and Post Order Traversal under 2 minutes]]></title><description><![CDATA[Let's don't waste time and finish the "confusing" topic of pre order, post order and in order traversal on binary trees. Most of my friends tell me that they often forget how each traversal works and ask me how to remember them. Well, here you go
Whe...]]></description><link>https://publications.theroyakash.com/tree-traversal-in-2-minutes</link><guid isPermaLink="true">https://publications.theroyakash.com/tree-traversal-in-2-minutes</guid><category><![CDATA[algorithms]]></category><category><![CDATA[Python]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[data structures]]></category><category><![CDATA[interview]]></category><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Mon, 24 May 2021 14:55:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621867743013/dXRWvQbHU.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let's don't waste time and finish the "confusing" topic of pre order, post order and in order traversal on binary trees. Most of my friends tell me that they often forget how each traversal works and ask me how to remember them. Well, here you go</p>
<p>When running through a tree (binary or binary search tree) we start from the root. Two things to do</p>
<ul>
<li>Add dummy nodes to the end of the leaf (Blue entry point in the image),</li>
<li>Then after marking those go to the root and start traversing.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621867384171/QwkrhQnfK.png" alt="O.png" /></p>
<p>Now arrange the queue of nodes like this if we visit</p>
<ul>
<li>the node for the first time we add that to the pre-order queue,</li>
<li>the node for the second time we add that to the in-order queue,</li>
<li>the node for the 3rd time we add that to the post-order queue.</li>
</ul>
<p>And now you have 3 queues each with pre-in-post order traversal path.</p>
<p>Also make a note that if the binary tree is a binary search tree, then the in-order traversal will give a sorted array. We can use this property to check if the binary tree is a binary search tree or not.</p>
<h2 id="heading-c-code">C Code</h2>
<p>Let's see some C code for this traversal algorithm</p>
<p>Tree Structure</p>
<pre><code class="lang-C"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">TreeNode</span> {</span>
    <span class="hljs-keyword">char</span> data;
    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">TreeNode</span> *<span class="hljs-title">left</span>, *<span class="hljs-title">right</span>;</span>
};

<span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">TreeNode</span> <span class="hljs-title">TreeNode</span>;</span>
</code></pre>
<p>Traversal Algorithms</p>
<pre><code class="lang-C"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">inOrderTraversal</span><span class="hljs-params">(TreeNode *nodePointer)</span></span>{

    <span class="hljs-keyword">if</span> (nodePointer != <span class="hljs-literal">NULL</span>) {
        inOrderTraversal(nodePointer-&gt;left);
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%c"</span>, nodePointer-&gt;data);
        inOrderTraversal(nodePointer-&gt;right);
    }
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">preOrderTraversal</span><span class="hljs-params">(TreeNode *nodePointer)</span></span>{

    <span class="hljs-keyword">if</span> (nodePointer != <span class="hljs-literal">NULL</span>) {
        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%c"</span>, nodePointer-&gt;data);
        preOrderTraversal(nodePointer-&gt;left);
        preOrderTraversal(nodePointer-&gt;right);
    }
}

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">postOrderTraversal</span><span class="hljs-params">(TreeNode *nodePointer)</span></span>{

    <span class="hljs-keyword">if</span> (nodePointer != <span class="hljs-literal">NULL</span>) {
        postOrderTraversal(nodePointer-&gt;left);
        postOrderTraversal(nodePointer-&gt;right);

        <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%c"</span>, nodePointer-&gt;data);
    }
}
</code></pre>
<h3 id="heading-more-on-this">More on this</h3>
<p>To see the proper algorithm on this visit <a target="_blank" href="https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/">here</a></p>
<p>Get all the updates directly into your inbox by subscribing to the blog.</p>
]]></content:encoded></item><item><title><![CDATA[Set-up an audio version of your blog articles [Works Automatically]]]></title><description><![CDATA[If you like the kind of articles I publish and follow my weekly machine learning issues subscribe to my newsletter.
If you want to listen to this article as audio while you read you can do it here
If you want your blog articles as audio and make them...]]></description><link>https://publications.theroyakash.com/set-up-an-audio-version-of-your-blog-articles-works-automatically</link><guid isPermaLink="true">https://publications.theroyakash.com/set-up-an-audio-version-of-your-blog-articles-works-automatically</guid><category><![CDATA[tools]]></category><category><![CDATA[General Advice]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Wed, 10 Feb 2021 07:09:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1612940767582/0abS3UT_8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you like the kind of articles I publish and follow my weekly machine learning issues subscribe to my newsletter.</p>
<div class="hn-embed-widget" id="newsletter"></div><p>If you want to listen to this article as audio while you read you can do it here</p>
<div class="hn-embed-widget" id="setup-audio"></div><p>If you want your blog articles as audio and make them available at the top of your post you can follow my steps. Currently, Hashnode has no support for audio embedding but we'll make it work. If you host your blogging in WordPress or Ghost you can embed an HTML5 Audio player directly into a post. Let's first generate all the audios.</p>
<p><a target="_blank" href="https://github.iamroyakash.com/AKDSFramework-docs/"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1613025383277/qT41p1MVB.png" alt="image.png" /></a></p>
<p>Last week I came across a platform called <a target="_blank" href="https://audiblogs.com/">Send As A Podcast</a>. It creates an audio version of the podcast and stores it in an amazon s3 bucket. Now once you've set up your audiblogs account, you need to do these steps to add the audio to your blog post.</p>
<ul>
<li>First create a public link for the draft of the blog. Here's how to do this
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1612939491364/91CN-xfRQ.png" alt="Screen Shot 2021-02-10 at 12.13.34 PM.png" /></li>
<li>Then you need to open the link and send this as a podcast via the audiblogs chrome extension.</li>
<li>Remember when you set up the audiblogs platform for your chrome you got a link that looks like this <code>https://rebrand.ly/......</code>.</li>
<li>Now open a chrome tab and go to that website. Now you have access to all the articles you've saved with this platform that will look like this
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1612939016434/2l3_CMA8z.png" alt="Screen Shot 2021-02-10 at 12.06.50 PM.png" /></li>
<li>Now look for the <code>enclosure URL</code> tag in the XML file.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1612939158362/gm5JKv1j-.png" alt="Screen Shot 2021-02-10 at 12.09.13 PM.png" /></li>
<li>Copy that <code>mp3</code> link, and with that create an HTML5 Widget like this<pre><code class="lang-HTML"><span class="hljs-tag">&lt;<span class="hljs-name">audio</span> <span class="hljs-attr">controls</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">source</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://s3.us-west-2.amazonaws.com/audiblogs/613be84b-99a8-48e1-864d-0e75fbd74eda.mp3"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"audio/mpeg"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">audio</span>&gt;</span>
</code></pre>
For hashnode users, until hashnode supports audio embedding in articles you have to create new custom widgets every time and embed the HTML in them or you can just add a link to the audio file at the top of the post. Now enjoy.</li>
</ul>
<h2 id="but-why-tho">But why tho?</h2>
<p>A natural-sounding audio experience can help your blog readers to engage more with a post. If you listen to a post while reading it, your mind can not be distracted from the around the world and you would engage more with the post. An audio experience for an engaging article engages people more with the blogs.</p>
]]></content:encoded></item><item><title><![CDATA[Priority Queues with Binary Heaps]]></title><description><![CDATA[I’m starting a data structure series where I introduce you to popular data structures and their implementations. I'll start with Priority Queues with Binary Heaps.
One of my favorite data structure is binary heaps. In this article I'll show you what ...]]></description><link>https://publications.theroyakash.com/pq-with-heaps</link><guid isPermaLink="true">https://publications.theroyakash.com/pq-with-heaps</guid><category><![CDATA[Python]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[data structures]]></category><category><![CDATA[coding]]></category><category><![CDATA[learn coding]]></category><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Thu, 07 Jan 2021 12:49:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1612346046384/mDh-w07Zd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I’m starting a data structure series where I introduce you to popular data structures and their implementations. I'll start with Priority Queues with Binary Heaps.</p>
<p>One of my favorite data structure is binary heaps. In this article I'll show you what is heap and how to make one with python and in the end I'll show you sorting technique that we can get for free just by building a heap.</p>
<h2 id="what-are-priority-queues">What are priority queues?</h2>
<p>A priority queue is a queue where the most important element is always at the front. The queue can be a max-priority queue (largest element first) or a min-priority queue (smallest element first).</p>
<p>So as a data structure designer you have the following options to design a priority queue:</p>
<ul>
<li>An max sorted array or min-sorted array, but downside is inserting new items is slow because they must be inserted in sorted order.</li>
<li>or an binary heap (max heap or min heap)</li>
</ul>
<p>Now the question arises what are heaps?
The heap is a natural data structure for a priority queue. In fact, the two terms are often used as synonyms. A heap is more efficient than a sorted array because a heap only has to be partially sorted. All heap operations are in the order of \(\log\) or linear.</p>
<p>Examples of algorithms that can benefit from a priority queue implemented as heap</p>
<ul>
<li>Dijkstra's algorithm for graph searching uses a priority queue to calculate the minimum cost.</li>
<li>A* pathfinding for artificial intelligence.</li>
<li>Huffman coding for data compression. This algorithm builds up a compression tree. It repeatedly needs to find the two nodes with the smallest frequencies that do not have a parent node yet.</li>
<li>Heap sort.</li>
</ul>
<h2 id="lets-design-some-heap">Let's design some heap</h2>
<p>First we need to design what our heaps should do design wise. It should have some APIs to</p>
<ol>
<li>Build an binary heap right from a unsorted pile of numbers.</li>
<li>Add a new number while maintaining the heap property with few swaps</li>
<li>Find a minimum or a maximum in the heap</li>
<li>Can remove that minimum or maximum from the heap and rearrange the heap to maintain it's heap property.</li>
</ol>
<p>With design of the heap software out of the way let's get to coding. I've built <a target="_blank" href="https://github.iamroyakash.com/AKDSFramework-docs/docs/index.html">AKDSFramework</a> which is a great resource for data structure and algorithm designs, I'll use my framework to show you building a heap.</p>
<h3 id="code">Code</h3>
<p>Let's first import heap class from AKDSFramework</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> AKDSFramework.structure <span class="hljs-keyword">import</span> MaxHeap, MinHeap
</code></pre>
<p>Now let’s build a max heap with 15 values.</p>
<pre><code class="lang-python">mxheap = MaxHeap([data**<span class="hljs-number">2</span> <span class="hljs-keyword">for</span> data <span class="hljs-keyword">in</span> range(<span class="hljs-number">15</span>)])
</code></pre>
<p>Now it’s important to call the build method on the heap to build the heap from an unsorted array of numbers. If the build is not done, printing and doing operations on heap will not be valid and will generate <code>HeapNotBuildError</code>. So always build your heap with <code>.heap()</code> method if you caused any change in the heap structure. Each time calling <code>.build()</code> method if there is one element of heap violation it will use \(O(\log n)\) time otherwise it's a linear operation for a <code>n</code> number of unordered elements.</p>
<pre><code class="lang-python">mxheap.build()
<span class="hljs-comment"># Now add few elements to the heap</span>
mxheap.add(<span class="hljs-number">12</span>)
mxheap.add(<span class="hljs-number">4</span>)
<span class="hljs-comment"># As the heap structure is changed so we have to call .build() again</span>
mxheap.build()
</code></pre>
<p>Now let's see the heap in a beautiful structure which is easy to understand.</p>
<pre><code class="lang-python">mxheap.prettyprint()
</code></pre>
<p>Now here is how the heap looks:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1610022112984/WAGnOvghe.png" alt="Screen Shot 2021-01-07 at 5.51.47 PM.png" /></p>
<p>Similarly you can implement the min heap by yourself.</p>
<h2 id="heapsort">Heapsort</h2>
<p>As you can see for a max heap every time after each build you'll get the maximum element from the head of the heap in constant \(O(1)\) time. And you build the heap everytime (<code>n</code> times) after removing the max item you'll have a sorted array sorted in \(O(n \log n)\) times.</p>
<p>Let's implement that with the help of min heaps:</p>
<p>I've already implemented heap sort with min heap in AKDSFramework</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> AKDSFramework.applications.sorting <span class="hljs-keyword">import</span> heapsort
<span class="hljs-keyword">import</span> random


array = [random.randint(<span class="hljs-number">1</span>, <span class="hljs-number">100</span>) <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)]
print(heapsort(array, visualize=<span class="hljs-literal">False</span>))
</code></pre>
<p>This return the sorted array like this <code>[23, 32, 37, 51, 55, 57, 59, 63, 78, 93]</code>.
Try to implement this by yourself if you get stuck here is a source code for implementing the heap sort with the built-in min heap API in AKDSFramework.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">heapsort</span>(<span class="hljs-params">array, visualize=False</span>):</span>
    <span class="hljs-string">r"""
    Heapsort implementation with min heap from AKDSFramework. Running time: :math:`O(N \log (n))`
        Args:
            - ``array`` (list): List of elements
            - ``vizualize`` (bool): Marked as False by default. If you want to vizualize set this as True
    """</span>
    <span class="hljs-keyword">if</span> visualize:
        iteration = <span class="hljs-number">0</span>

    ret = []

    mnheap = MinHeap(array)
    mnheap.build()

    <span class="hljs-keyword">while</span> len(mnheap) &gt;= <span class="hljs-number">1</span>:
        <span class="hljs-keyword">if</span> len(mnheap) == <span class="hljs-number">1</span>:
            ret.append(mnheap[<span class="hljs-number">0</span>])
            <span class="hljs-keyword">break</span>

        <span class="hljs-comment"># O(1) time access of minimum element</span>
        root = mnheap.get_root()
        ret.append(root)
        <span class="hljs-comment"># O(log n) operation</span>
        mnheap.delete_root()
        <span class="hljs-comment"># Constant operation, deleting at the beginning,</span>
        <span class="hljs-comment"># by this time you need to call .build() again to </span>
        <span class="hljs-comment"># rebuild the heap property</span>
        mnheap.build()        <span class="hljs-comment"># O(log N) for a single violation</span>

        <span class="hljs-keyword">if</span> visualize:
            print(<span class="hljs-string">"-"</span>*<span class="hljs-number">40</span>)
            print(<span class="hljs-string">f'End of Iteration: <span class="hljs-subst">{iteration}</span>'</span>)
            print(<span class="hljs-string">f'Currently heap: <span class="hljs-subst">{mnheap}</span>'</span>)
            print(<span class="hljs-string">f'Our returning array: <span class="hljs-subst">{ret}</span>'</span>)

            iteration += <span class="hljs-number">1</span>

    <span class="hljs-keyword">return</span> ret
</code></pre>
<h2 id="more-readings">More readings</h2>
<p>If you want to implement heaps all by yourself I'd recommend you to check out the following resources:</p>
<ul>
<li>Heaps on <a target="_blank" href="https://en.wikipedia.org/wiki/Heap_(data_structure">Wikipedia</a>)</li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=B7hVxCmfPtM">MIT Lecture on heaps</a></li>
<li>Source code of the AKDSFramework's Min and Max Heap implementations <a target="_blank" href="https://github.com/theroyakash/AKDSFramework/blob/main/AKDSFramework/structure/heap.py">here</a>. Implementations are based on MIT lecture video.</li>
</ul>
<h2 id="thanks-for-reading">Thanks for reading</h2>
<p>If you find this helpful please subscribe to my newsletter. Please feel free to reach out to me on <a target="_blank" href="https://www.twitter.com/theroyakash">twitter</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Introducing an efficient Big O analyzer]]></title><description><![CDATA[Introducing an efficient Big O analyzer, a premium state-of-the-art AKDSFramework feature to analyze Big O for any function without any human intervention.
As you already know calculating big O is a big part of what we do to approximate the running t...]]></description><link>https://publications.theroyakash.com/introducing-an-efficient-big-o-analyzer</link><guid isPermaLink="true">https://publications.theroyakash.com/introducing-an-efficient-big-o-analyzer</guid><category><![CDATA[Christmas Hackathon]]></category><category><![CDATA[Python]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[python projects]]></category><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Tue, 29 Dec 2020 13:07:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1612345892127/ee0At3zE7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Introducing an efficient Big O analyzer, a premium state-of-the-art <a target="_blank" href="https://github.com/theroyakash/AKDSFramework">AKDSFramework</a> feature to analyze Big O for any function without any human intervention.</p>
<p>As you already know calculating big O is a big part of what we do to approximate the running time of an algorithm in worst cases. But most of it is done by hand tracing step by step manually. I'm going to propose an analytical approach to compute big O with respect to one expanding variable. Let's see what I mean with some examples</p>
<ol>
<li>Sorting a sequence of numbers (Big O is \(O(n \log n)\) with respect to the sequence's length (n))</li>
<li>Finding the maximum element of a given array is \(O(n)\) with respect the length of the array.</li>
<li>Finding the last element of a singly linked list is \(O(n)\) with respect to the length of the list.</li>
</ol>
<p>So in the above cases I'm calling the sequence of numbers the "expanding variables" because we are calculating how the algorithm would perform when these "expanding variables" grows towards big sizes.</p>
<p>Now let's create a Big O analyzer.</p>
<h1 id="designing-the-big-o-analyser-system">Designing the Big O analyser system</h1>
<p>Our big O analyser system has these following parts</p>
<ul>
<li>A function that would make a dictionary and record how much time the function is taking for different size of inputs.</li>
<li>Another function that would generate different size of inputs that can be fed into the function. Let's call it a generator.</li>
<li>Another function that would interpret the execution times and fit the times into a definitive time complexity with respect to the expanding variable.</li>
</ul>
<p>Let's see an example to clarify this thing:</p>
<p>Let's say we are tasked to find the complexity of the python function <code>sorted()</code>. Now we identify what's our expanding variable?</p>
<p>For the function sorted it sorts a sequence of data, so the expanding variable would be the sequence of numbers. So now let's import an generator that is built into <a target="_blank" href="https://github.com/theroyakash/AKDSFramework">AKDSFramework</a></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> AKDSFramework.applications.complexity_analysis.data_generators <span class="hljs-keyword">import</span> integer_sequence
</code></pre>
<p>Now armed with integer_sequence that can generate sequence of integers with length of any number we create an instance of the <code>integer_sequence</code> like this:</p>
<pre><code class="lang-python">int_generator = <span class="hljs-keyword">lambda</span> n: integer_sequence(lb=<span class="hljs-number">1</span>, ub=<span class="hljs-number">200000</span>, size=n)
</code></pre>
<p>Now this int_generator can create a random sequence of length <code>n</code> and individual elements are ranging from 1 to 200000.</p>
<p>Now our job is to make a dictionary and record how much time the function is taking for different size of inputs. From the previous piece of code we already know that we can generate different size of inputs. Now it's time to create the dictionary. For that we need to do the followings</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> AKDSFramework.applications.complexity_analysis.analyser <span class="hljs-keyword">import</span> runtimedict
</code></pre>
<p>Now we feed the function and any other keyword arguments for the function into <code>runtimedict</code> method.</p>
<h2 id="the-run-time-dictionary">The run-time dictionary</h2>
<p><code>runtimedict</code> method takes in a few arguments these are:</p>
<ul>
<li><code>func</code>: The function for which you want to make the execution time dictionary. </li>
<li><code>pumping_lower_bound</code>: Lowest size of the expanding variable. For example if you have to find the execution time for some size of arrays from where you would start. </li>
<li><code>pumping_upper_bound</code>: Largest size of the expanding variable. For example if you have to find the execution time for some size of arrays where you would stop. </li>
<li><code>total_measurements</code>: From lowest size of array to largest size of array how many measurements you want to do? </li>
<li><code>pumping</code>: Among all the keyword arguments what variable needs to be pumped meaning what arguments is the expanding variable. Put the name of the variable in strings. </li>
<li>**kwargs: All the arguments of the functions.</li>
</ul>
<p>Let's take the example of <code>sorted</code>. Sorted function takes in <code>iterable</code> as the keyword argument for the sequence of numbers so to make the run time dictionary we write this:</p>
<ul>
<li>We'll record 200 measurements.</li>
<li>Our array size will start from 1000</li>
<li>Our array size will end to 5000</li>
</ul>
<p>So the code would be</p>
<pre><code class="lang-python"><span class="hljs-comment"># The integer generator from before</span>
int_generator = <span class="hljs-keyword">lambda</span> n: int_generator(<span class="hljs-number">1</span>, <span class="hljs-number">200000</span>, n)

<span class="hljs-comment"># And the Run time dictionary</span>
rtdc = runtimedict(sorted, <span class="hljs-number">1000</span>, <span class="hljs-number">5000</span>, <span class="hljs-number">200</span>, pumping=<span class="hljs-string">'iterable'</span>, iterable=int_generator)
</code></pre>
<p>Now to fit the complexity we need the following lines of code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> AKDSFramework.applications.complexity_analysis.analyser <span class="hljs-keyword">import</span> run_inference_on_complexity

run_inference_on_complexity(rtdc)
</code></pre>
<h3 id="output">Output</h3>
<pre><code class="lang-bash">Calculating complexity: 100%|██████████| 7/7 [00:00&lt;00:00, 2618.63it/s]
O(N <span class="hljs-built_in">log</span> N)
</code></pre>
<p>As you can see that our analysis of sorted function is \(O(n \log n)\) which is actually true.</p>
<h3 id="another-example">Another example</h3>
<p>Now let's take another example of bubble sort and insertion sort. Both are order \(O(n^2)\)</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> AKDSFramework.applications.sorting <span class="hljs-keyword">import</span> bubblesort, insertionsort

rtdc = runtimedict(insertionsort, <span class="hljs-number">10</span>, <span class="hljs-number">2000</span>, <span class="hljs-number">200</span>, pumping=<span class="hljs-string">'array'</span>, array=int_generator, visualize=<span class="hljs-literal">False</span>, maintain_iter_dict=<span class="hljs-literal">False</span>)
run_inference_on_complexity(rtdc)
</code></pre>
<h3 id="output">Output</h3>
<pre><code class="lang-bash">Processing: 100%|██████████| 200/200 [00:12&lt;00:00, 16.17it/s]
Calculating complexity: 100%|██████████| 7/7 [00:00&lt;00:00, 2285.37it/s]
O(N^2)
</code></pre>
<h2 id="bubble-sort">Bubble sort</h2>
<pre><code class="lang-python">rtdc = runtimedict(bubblesort, <span class="hljs-number">1000</span>, <span class="hljs-number">5000</span>, <span class="hljs-number">200</span>, pumping=<span class="hljs-string">'array'</span>, array=int_generator, visualize=<span class="hljs-literal">False</span>, maintain_iter_dict=<span class="hljs-literal">False</span>)

run_inference_on_complexity(rtdc)
</code></pre>
<h3 id="output">Output</h3>
<pre><code class="lang-bash">Processing: 100%|██████████| 200/200 [03:23&lt;00:00,  1.02s/it]
Calculating complexity: 100%|██████████| 7/7 [00:00&lt;00:00, 3031.82it/s]
O(N^2)
</code></pre>
<h1 id="inner-workings">Inner workings</h1>
<p>So we can say the big O complexity analysis is working. Let's see the inner workings of this module:</p>
<ol>
<li>First we calculate the runtime for different size of array.</li>
<li>Next we fit the size and time to return the least-squares solution to a linear matrix equation. Now by fitting we mean in separate instances we transform the size to order \(O(n)\) or \(O(n^2)\) or \(O(n^3)\) or \(O(n \log n)\) or \(O(\log n)\) or \(O(c^n)\) then we look at which one is most fitted to a straight line with the time. The most fitted one will be our big O because the time would be in the same order.</li>
<li>We return the most fitted complexity.</li>
</ol>
<p>To see which one fits better we use <code>numpy.linalg.lstsq</code> to return the least-squares solution to a linear matrix equation. Returned residual is minimum means that the equation fits better to a linear equation. More about this method <a target="_blank" href="https://numpy.org/doc/stable/reference/generated/numpy.linalg.lstsq.html">here</a></p>
<h1 id="installation">Installation</h1>
<ul>
<li>First download/clone this repo like git clone <code>https://github.com/theroyakash/AKDSFramework.git</code></li>
<li>Now uninstall if any previous version installed <code>pip3 uninstall AKDSFramework</code></li>
<li>Now install fresh on your machine <code>pip3 install -e AKDSFramework</code></li>
</ul>
<h3 id="alternate-installation">Alternate installation</h3>
<p>This is easier to install but a bit slower in the installation time.
<code>pip3 install https://github.com/theroyakash/AKDPRFramework/tarball/main</code></p>
<h4 id="first-code-check-the-version">First code, Check the version</h4>
<p>Now to check whether your installation is completed without error import AKDSFramework</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> AKDSFramework
print(<span class="hljs-string">'AKDSFramework Version is --&gt; '</span> + AKDSFramework.__version__)
</code></pre>
<p>What you contribute is the only resource behind these material. Please support me on gumroad</p>
<div class="hn-embed-widget" id="gumroad"></div>]]></content:encoded></item><item><title><![CDATA[Speed up your python code by caching]]></title><description><![CDATA[Let's say you have a function that is a super-slow function. Not sure how you can find which is a super slow function? Measure it with this.
Now there is now way you can optimize the function, what you can do instead is that you can store results fro...]]></description><link>https://publications.theroyakash.com/cache-your-code</link><guid isPermaLink="true">https://publications.theroyakash.com/cache-your-code</guid><category><![CDATA[Python]]></category><category><![CDATA[caching]]></category><category><![CDATA[speed]]></category><category><![CDATA[life-hack]]></category><category><![CDATA[Christmas Hackathon]]></category><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Sat, 26 Dec 2020 09:32:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1608975131733/hBuGo7qzv.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let's say you have a function that is a super-slow function. Not sure how you can find which is a super slow function? Measure it with <a target="_blank" href="https://publications.iamroyakash.com/benchmark-your-python-program">this.</a></p>
<p>Now there is now way you can optimize the function, what you can do instead is that you can store results from a previous computation and reuse those results in a new computation to find solutions to other problem.</p>
<h1 id="what-we-are-gonna-see-in-this-post">What we are gonna see in this post?</h1>
<ul>
<li>We'll implement finding n-th fibonacci number problem</li>
<li>We'll find out how much time it takes to compute 40th fibonacci number.</li>
<li>and at the end we'll make our code 400k times faster. (and yeah you are reading it right)</li>
</ul>
<h1 id="lets-get-to-code">Let's get to code</h1>
<p>Let's create world's worst fibonacci series computation code. The algorithm might look like this:</p>
<pre><code><span class="hljs-string">FIBONACCI</span> <span class="hljs-string">(n):</span>
    <span class="hljs-string">if</span> <span class="hljs-string">n</span> <span class="hljs-string">-&gt;</span> <span class="hljs-attr">0:</span> <span class="hljs-string">f</span> <span class="hljs-string">=</span> <span class="hljs-number">0</span>
    <span class="hljs-string">elif</span> <span class="hljs-string">n</span> <span class="hljs-string">-&gt;</span> <span class="hljs-attr">1:</span> <span class="hljs-string">f</span> <span class="hljs-string">=</span> <span class="hljs-number">1</span>
    <span class="hljs-attr">else:</span>
        <span class="hljs-string">f</span> <span class="hljs-string">=</span> <span class="hljs-string">FIBONACCI(n</span> <span class="hljs-bullet">-</span> <span class="hljs-number">1</span><span class="hljs-string">)</span> <span class="hljs-string">+</span> <span class="hljs-string">FIBONACCI</span> <span class="hljs-string">(n</span> <span class="hljs-bullet">-</span> <span class="hljs-number">2</span><span class="hljs-string">)</span>
    <span class="hljs-string">return</span> <span class="hljs-string">f</span>
</code></pre><p>This is a correct algorithm for fibonacci. But if you see the recurrence relation <code>T(n) = T(n-1) + T(n-2) + O(1)</code> you can see that the code is running in exponential time <code>O(2^N)</code> which is really really bad.</p>
<p>The equivalent python code would be:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fibonacci</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">if</span> n == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
    <span class="hljs-keyword">elif</span> n == <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> fibonacci(n - <span class="hljs-number">1</span>) + fibonacci(n - <span class="hljs-number">2</span>)
</code></pre><p>If you draw a recursion tree you can find that you are computing same computation over and over again in different trees. Let's see what I mean:</p>
<pre><code class="lang-bash">+--+-----------+-----------+--------+-----------+-----------+--+
|  |           |           | Fib(n) |           |           |  |
+--+-----------+-----------+--------+-----------+-----------+--+
|  |           | Fib (n-1) |        | Fib (n-2) |           |  |
+--+-----------+-----------+--------+-----------+-----------+--+
|  | Fib (n-2) | Fib (n-3) |        | Fib (n-3) | Fib (n-4) |  |
+--+-----------+-----------+--------+-----------+-----------+--+
</code></pre>
<p>See for calculating <code>fib(n)</code> you are calculating <code>Fib (n-1)</code> and <code>Fib (n-2)</code>. In a separate computation you are computing <code>Fib (n-2)</code> for that you are computing <code>Fib (n-3)</code> and <code>Fib (n-4)</code>.</p>
<p>If you had <code>Fib (n-2)</code> from the previous computation stored, you wouldn't have to recompute that <code>Fib (n-2)</code> and it's subsequent branches. So you would've saved a lot of time by just not recomputing anything.</p>
<p>Let's without caching how much time it would take to compute <code>fib(40)</code> that is 50th fibonacci number:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> time

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fibonacci</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">if</span> n == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
    <span class="hljs-keyword">elif</span> n == <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> fibonacci(n - <span class="hljs-number">1</span>) + fibonacci(n - <span class="hljs-number">2</span>)


start = time.perf_counter()
print(fibonacci(<span class="hljs-number">40</span>))
end = time.perf_counter()

print(<span class="hljs-string">f"Computed in <span class="hljs-subst">{(end - start) * <span class="hljs-number">1000</span>}</span> ms"</span>)
</code></pre>
<p>Total time for computation is 40.635853995000005 seconds. So our python program is taking 40 seconds to compute fib(40). Now let's store intermediate step's data in a dictionary so that we can retrieve those data at a later time in constant time.</p>
<h1 id="creating-a-decorator">Creating a decorator</h1>
<p> <a target="_blank" href="https://github.com/theroyakash/AKDSFramework">AKDSFramework</a> has a built in decorator for caching purposes. You can find AKDSFramework <a target="_blank" href="https://github.com/theroyakash/AKDSFramework">here</a>. You can pretty much use this on any python function as you like, small-big-has other dependency anything.</p>
<p>If you install it you can get the benchmarking of python programs, caching python functions and implementation of several data structures and algorithms using best practices in it.</p>
<p>If you don't wish to use my package at the end of the blog I'll paste the source code for @cached decorator.</p>
<p>Now let's import the cached decorator from AKDSFramework</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> AKDSFramework.applications.decorators <span class="hljs-keyword">import</span> cached
</code></pre>
<p>Now with the cached decorator let's implement the fibonacci series code and see how much time it takes to find fib(40)</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> time

<span class="hljs-meta">@cached</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fibonacci</span>(<span class="hljs-params">n</span>):</span>
    <span class="hljs-keyword">if</span> n == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
    <span class="hljs-keyword">elif</span> n == <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> fibonacci(n - <span class="hljs-number">1</span>) + fibonacci(n - <span class="hljs-number">2</span>)


start = time.perf_counter()
print(fibonacci(<span class="hljs-number">40</span>))
end = time.perf_counter()

print(<span class="hljs-string">f"Computed in <span class="hljs-subst">{(end - start)}</span> seconds"</span>)
</code></pre>
<p>Now it takes around 8.945500000000217e-05 seconds. Which is 400k times faster to compute.</p>
<h1 id="source-code">Source code</h1>
<p>If you don't wish to use our AKDSFramework here is the source code for the caching decorator.</p>
<p>Our cache storage stores unlimited data, but if your program has limited storage you can update the dictionary to hold predefined amount of data and if one data is not used for long enough you can kick it out with pre defined cache replacement policies.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">cached</span>(<span class="hljs-params">func</span>):</span>
    cache = dict()

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">caching</span>(<span class="hljs-params">*args</span>):</span>
        <span class="hljs-keyword">if</span> args <span class="hljs-keyword">in</span> cache:
            <span class="hljs-keyword">return</span> cache[args]
        result = func(*args)
        cache[args] = result
        <span class="hljs-keyword">return</span> result

    <span class="hljs-keyword">return</span> caching
</code></pre>
]]></content:encoded></item><item><title><![CDATA[How to benchmark your python program?]]></title><description><![CDATA[Let's say you have a really slow program and you want to benchmark where your program is taking most of the time to run. If you can find that you can just optimize that part of the program to run faster.
There is couple of way of doing this going thr...]]></description><link>https://publications.theroyakash.com/benchmark-your-python-program</link><guid isPermaLink="true">https://publications.theroyakash.com/benchmark-your-python-program</guid><category><![CDATA[Python 3]]></category><category><![CDATA[Python]]></category><category><![CDATA[Benchmark]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[life-hack]]></category><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Sat, 21 Nov 2020 09:21:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1605950239655/3jwOT4SQD.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let's say you have a really slow program and you want to benchmark where your program is taking most of the time to run. If you can find that you can just optimize that part of the program to run faster.</p>
<p>There is couple of way of doing this going through this manually or using some kind of library like cProfile to generate a report on the function's workings.</p>
<h1 id="generating-reports">Generating reports</h1>
<p>I've written all necessary code to run this in my package <code>AKDSFramework</code>.
AKDSFramework can be found  <a target="_blank" href="https://github.com/theroyakash/AKDSFramework">here.</a> You can pretty much use this on any python function as you like, small-big-has other dependency anything.</p>
<p>If you install it you can get the benchmarking and implementation of several data structures and algorithms using best practices in it.</p>
<p>If you don't wish to use my package at the end of the blog I'll paste the source code for <code>@benchmark</code> decorator.</p>
<h1 id="example-implementation">Example implementation</h1>
<p>We gonna see an example of implementation of benchmarking by building a max heap and adding 2 numbers to the heap and again building it.</p>
<p>To make max heaps I'll use AKDSFramework, let's create a heap and build it now with around 600 elements.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> AKDSFramework.applications.decorators <span class="hljs-keyword">import</span> benchmark
<span class="hljs-keyword">from</span> AKDSFramework.structure <span class="hljs-keyword">import</span> MaxHeap

<span class="hljs-meta">@benchmark</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">buildHeap</span>(<span class="hljs-params">array</span>):</span>
    h = MaxHeap(array)
    h.build()

    h.add(<span class="hljs-number">68</span>)
    h.add(<span class="hljs-number">13</span>)
    h.build()

buildHeap([data**<span class="hljs-number">2</span> <span class="hljs-keyword">for</span> data <span class="hljs-keyword">in</span> range(<span class="hljs-number">601</span>)])
</code></pre>
<p>Notice the <code>@benchmark</code> decorator at the beginning of the declaration of the function, that calls cProfile to start calculating what taking what.</p>
<p>Now running the code will output a report in the console like this:</p>
<pre><code class="lang-bash">       3597 <span class="hljs-keyword">function</span> calls (3003 primitive calls) <span class="hljs-keyword">in</span> 0.002 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(<span class="hljs-keyword">function</span>)
        1    0.000    0.000    0.002    0.002 &lt;ipython-input-18-1d08ee399432&gt;:4(buildHeap)
        2    0.000    0.000    0.002    0.001 /opt/venv/lib/python3.7/site-packages/AKDSFramework/structure/heap.py:136(build)
 1195/601    0.001    0.000    0.001    0.000 /opt/venv/lib/python3.7/site-packages/AKDSFramework/structure/heap.py:153(heapify)
     1195    0.000    0.000    0.000    0.000 /opt/venv/lib/python3.7/site-packages/AKDSFramework/structure/heap.py:67(get_left_child)
     1195    0.000    0.000    0.000    0.000 /opt/venv/lib/python3.7/site-packages/AKDSFramework/structure/heap.py:53(get_right_child)
        2    0.000    0.000    0.000    0.000 /opt/venv/lib/python3.7/site-packages/AKDSFramework/structure/heap.py:26(add)
        1    0.000    0.000    0.000    0.000 /opt/venv/lib/python3.7/site-packages/AKDSFramework/structure/heap.py:128(__init__)
        1    0.000    0.000    0.000    0.000 /opt/venv/lib/python3.7/site-packages/AKDSFramework/structure/heap.py:21(__init__)
        1    0.000    0.000    0.000    0.000 {method <span class="hljs-string">'disable'</span> of <span class="hljs-string">'_lsprof.Profiler'</span> objects}
        2    0.000    0.000    0.000    0.000 {method <span class="hljs-string">'append'</span> of <span class="hljs-string">'list'</span> objects}
        2    0.000    0.000    0.000    0.000 {built-in method builtins.len}
</code></pre>
<p>This has all the call's report and how much time it's taking. If you see the second last function call <code>{method 'append' of 'list' objects}</code> see that's called 2 times total as we are appending 2 elements.</p>
<p>So this way you can see how much each function taking time and how many times they are called. If you wish you can reduce the number of calls or use a different approach to solve the part where it's slow.</p>
<p>AKDSFramework's all implementations of data structures and algorithms are super optimized so you can't find any bottle neck when using <code>@benchmark</code> on our function calls.</p>
<p>If you don't wish to install AKDSFramework here is the <code>@benchmark</code> decorator source code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> cProfile
<span class="hljs-keyword">import</span> pstats
<span class="hljs-keyword">import</span> io

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">benchmark</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-string">"""
    AKDSFramework default benchmark profiler. Implemented with cProfile and pstats.
    """</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">profiler</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        profiler = cProfile.Profile()
        profiler.enable()
        returnvalue = func(*args, **kwargs)
        profiler.disable()

        stringIO = io.StringIO()

        ps = pstats.Stats(profiler, stream=stringIO).sort_stats(<span class="hljs-string">"cumulative"</span>)
        ps.print_stats()
        print(stringIO.getvalue())

        <span class="hljs-keyword">return</span> returnvalue

    <span class="hljs-keyword">return</span> profiler
</code></pre>
]]></content:encoded></item><item><title><![CDATA[What is logarithms in time complexity means?]]></title><description><![CDATA[If we talk about some sorting algorithms we'll see their running time is in the order of \(O(n log(n))\) time. In this article we'll talk why logarithm time is useful and how it's working?
Let's imagine the following task
for i in range(10):
    prin...]]></description><link>https://publications.theroyakash.com/log-time-complexity</link><guid isPermaLink="true">https://publications.theroyakash.com/log-time-complexity</guid><category><![CDATA[algorithms]]></category><category><![CDATA[Python 3]]></category><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Sat, 14 Nov 2020 05:38:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1605330234863/ZM7D0Tlr5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If we talk about some sorting algorithms we'll see their running time is in the order of \(O(n log(n))\) time. In this article we'll talk why logarithm time is useful and how it's working?</p>
<p>Let's imagine the following task</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
    print(i)
</code></pre>
<p>This function will print the number <code>i</code> 10 times. Now run this for 100 times so it'll run for 100 times. So you can see that the running time growing linearly with respect to the input size.</p>
<p>So we can write the following table </p>
<ul>
<li>1 unit of time to complete if you have 1 elements.</li>
<li>2 unit of time to complete if you have 2 elements.</li>
<li>3 unit of time to complete if you have 3 elements.</li>
<li>4 unit of time to complete if you have 4 elements.</li>
<li>5 unit of time to complete if you have 5 elements.</li>
</ul>
<p>.....................</p>
<ul>
<li>\(n\) unit of time to complete if you have \(n\) elements.</li>
</ul>
<p>Now let's imagine the following task</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
    <span class="hljs-keyword">for</span> y <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
        print(i)
</code></pre>
<p>This program has order of \(n^2\) running time because the time of running the function will grow with the square of the input size.</p>
<p>So we can write the following table </p>
<ul>
<li>1 unit of time to complete if you have 1 elements.</li>
<li>4 unit of time to complete if you have 2 elements.</li>
<li>9 unit of time to complete if you have 3 elements.</li>
<li>16 unit of time to complete if you have 4 elements.</li>
<li>25 unit of time to complete if you have 5 elements.</li>
</ul>
<p>.....................</p>
<ul>
<li>\(n^2\) unit of time to complete if you have \(n\) elements.</li>
</ul>
<h3 id="now-lets-talk-about-log-n-time">Now let's talk about log n time</h3>
<p>Now similar to these two imagine a function that does the following</p>
<ul>
<li>1 unit of time to complete if you have 2 elements.</li>
<li>2 unit of time to complete if you have 4 elements.</li>
<li>3 unit of time to complete if you have 8 elements.</li>
<li>4 unit of time to complete if you have 16 elements.</li>
<li>5 unit of time to complete if you have 32 elements.</li>
</ul>
<p>.....................</p>
<ul>
<li>\(n\) unit of time to complete if you have \(2^n\) elements.</li>
</ul>
<p>So if you analyze this pattern you'll see that the next iteration of the loop takes half the time the current one is going to take.</p>
<p>When it comes to Asymptotic analysis, we just call \(\log(n)\) which can be basically any base. But since we computer scientists use binary trees, we end up with \(\log_2(n)\) most of the times which we just term \(\log(n)\).</p>
<p>We talked about n log n time in the beginning of the article with is a linearithmic time problem. So you can construct your n log n problems like this</p>
<pre><code>a <span class="hljs-keyword">loop</span> that runs n times{
    -&gt; a program that runs <span class="hljs-keyword">in</span> <span class="hljs-keyword">log</span> n <span class="hljs-type">time</span> complexity
}
</code></pre><p>A loop is running n times and a log n algorithm is running in that loop so the overall algorithm is = \(O(n \log n)\).</p>
<h3 id="more-resources">More resources</h3>
<p>You can learn more about this here</p>
<ul>
<li>My other article on big O notation <a target="_blank" href="https://sites.google.com/view/algobytheroyakash/algorithms/big-o-notations">here</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Big_O_notation">Wikipedia</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[4 Line python-based URL shortener]]></title><description><![CDATA[Let's build an URL shortener with just 4 lines of code. I'll keep it as simple as possible.
Inspiration
I was building a discord BOT that has the feature of sending top news article in a given hour, but the URLs were too long so it was looking bad in...]]></description><link>https://publications.theroyakash.com/4-line-urlshortener</link><guid isPermaLink="true">https://publications.theroyakash.com/4-line-urlshortener</guid><category><![CDATA[Python 3]]></category><category><![CDATA[Python]]></category><category><![CDATA[python beginner]]></category><category><![CDATA[python projects]]></category><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Mon, 02 Nov 2020 20:43:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1604427696691/AaHKZBuA_.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let's build an URL shortener with just 4 lines of code. I'll keep it as simple as possible.</p>
<h3 id="inspiration">Inspiration</h3>
<p>I was building a <a target="_blank" href="https://bit.ly/inviteblyat">discord BOT</a> that has the feature of sending top news article in a given hour, but the URLs were too long so it was looking bad in a discord chat. So I thought of making an shortener service based on tiny-url to beautify those long a** URLs.</p>
<h3 id="requirements">Requirements</h3>
<ul>
<li><code>contextlib</code> for utilities for with-statement contexts,</li>
<li>and <code>urllib</code> module which are built-in. So nothing needed to be installed.</li>
</ul>
<h3 id="code">Code</h3>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> contextlib 
<span class="hljs-keyword">from</span> urllib.parse <span class="hljs-keyword">import</span> urlencode
<span class="hljs-keyword">from</span> urllib.request <span class="hljs-keyword">import</span> urlopen 

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">tinyURLOf</span>(<span class="hljs-params">url</span>):</span>
    encoded_url = urlencode({<span class="hljs-string">'url'</span>: url})
    request_url = <span class="hljs-string">'http://tinyurl.com/api-create.php?'</span> + str(encoded_url)
    <span class="hljs-keyword">with</span> contextlib.closing(urlopen(request_url)) <span class="hljs-keyword">as</span> response:                       
        <span class="hljs-keyword">return</span> response.read().decode(<span class="hljs-string">'utf-8 '</span>)
</code></pre>
<p>So now run the function <code>tinyURLOf(url='YOUR_URL_HERE')</code> to get the result back.</p>
]]></content:encoded></item><item><title><![CDATA[Popular Activation Functions & Implementation]]></title><description><![CDATA[Here in this post we'll be implementing popular deep learning activation functions from the ground up using numpy.
So for you to follow this post you need to things:

numpy and
Some free time of yours.

If you have written any deep learning code befo...]]></description><link>https://publications.theroyakash.com/popular-activation-functions-and-implementation</link><guid isPermaLink="true">https://publications.theroyakash.com/popular-activation-functions-and-implementation</guid><category><![CDATA[Deep Learning]]></category><category><![CDATA[numpy]]></category><category><![CDATA[Python 3]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[neural networks]]></category><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Thu, 22 Oct 2020 17:09:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1604350233217/QL75cfugv.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Here in this post we'll be implementing popular deep learning activation functions from the ground up using numpy.</p>
<p>So for you to follow this post you need to things:</p>
<ul>
<li><code>numpy</code> and</li>
<li>Some free time of yours.</li>
</ul>
<p>If you have written any deep learning code before you likely have used these activations:</p>
<ul>
<li>Softmax</li>
<li>ReLU, LeakyReLU</li>
<li>and the good-old Sigmoid activation.</li>
</ul>
<p>In this post I'll implement all these activation functions with numpy and also the derivative of these for the back-propagation.</p>
<h2 id="relu">ReLU</h2>
<p>Let's get the easy one out first. ReLU is called rectified linear unit, where:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603384480484/kbISErB8u.png" alt="Screen Shot 2020-10-22 at 10.04.36 PM.png" /></p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ReLU</span>:</span>
    <span class="hljs-string">"""Applies the rectified linear unit function element-wise. 
        ReLU operation is defined as the following
    """</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-keyword">return</span> np.where(x &gt;= <span class="hljs-number">0</span>, x, <span class="hljs-number">0</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">gradient</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-string">"""
        Computes Gradient of ReLU
            Args:
                x: input tensor
            Returns:
                Gradient of X
        """</span>
        <span class="hljs-keyword">return</span> np.where(x &gt;= <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>)
</code></pre>
<p>Usage:</p>
<pre><code class="lang-python">relu = ReLU()
z = np.array([<span class="hljs-number">0.1</span>, <span class="hljs-number">-0.4</span>, <span class="hljs-number">0.7</span>, <span class="hljs-number">1</span>])
print(relu(z))      <span class="hljs-comment"># ---&gt; array([0.1, 0. , 0.7, 1. ])</span>
print(relu.gradient(z))   <span class="hljs-comment"># ---&gt; array([1, 0, 1, 1])</span>
</code></pre>
<h2 id="sigmoid">Sigmoid</h2>
<p>Sigmoid function is defined as the following</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603384729593/86jxayAM8.png" alt="Screen Shot 2020-10-22 at 10.08.45 PM.png" /></p>
<p>The main reason why we use sigmoid function is because it exists between (0 to 1). Therefore, it is especially used for models where we have to predict the probability as an output.Since probability of anything exists only between the range of 0 and 1, sigmoid is the right choice. The function is differentiable.That means, we can find the slope of the sigmoid curve at any two points. The function is monotonic but function’s derivative is not.
The logistic sigmoid function can cause a neural network to get stuck at the training time. The softmax function is a more generalized logistic activation function which is used for multi-class classification.</p>
<p>The element wise <code>exp</code> can be done like the following, and if you calculate the derivative you can find that <code>d/dx sigmoid(x) = sigmoid(x) *(1- sigmoid(x))</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603386331423/KaPNq9yvJ.png" alt="Screen Shot 2020-10-22 at 10.35.21 PM.png" /></p>
<p>So let's write up the activation function for sigmoid operation:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Sigmoid</span>:</span>
    <span class="hljs-string">"""
    Applies the element-wise function
    Shape:
        - Input: :math:`(N, *)` where `*` means, any number of additional
          dimensions
        - Output: :math:`(N, *)`, same shape as the input
    """</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span> / (<span class="hljs-number">1</span> + np.exp(-x))

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">gradient</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-string">r"""Computes Gradient of Sigmoid
        .. math::
            \frac{\partial}{\partial x} \sigma(x) = \sigma(x)* \left (  1- \sigma(x)\right)
        Args:
            x: input tensor
        Returns:
            Gradient of X
        """</span>

        <span class="hljs-keyword">return</span> self.__call__(x) * (<span class="hljs-number">1</span> - self.__call__(x))
</code></pre>
<p>and the usage would be like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np

z = np.array([<span class="hljs-number">0.1</span>, <span class="hljs-number">0.4</span>, <span class="hljs-number">0.7</span>, <span class="hljs-number">1</span>])
sigmoid = Sigmoid()
return_data = sigmoid(z)

print(return_data)          <span class="hljs-comment"># -&gt; array([0.52497919, 0.59868766, 0.66818777, 0.73105858])</span>
print(sigmoid.gradient(z))  <span class="hljs-comment"># -&gt; array([0.24937604, 0.24026075, 0.22171287, 0.19661193])</span>
</code></pre>
<h2 id="leakyrelu">LeakyReLU</h2>
<p>LeakyReLU operation is similar to the ReLU operation also called the Leaky version of a Rectified Linear Unit. It essentially instead of putting zeros everywhere it sees &lt; 0, it puts an predefined -ve slope like -0.1 or -0.2 etc.
You mention an alpha, and it'll put -alpha where X &lt; 0.</p>
<p>The following image shows the difference between ReLU and LeakyReLU</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603385917652/v2BXM0WID.jpeg" alt="1_A_Bzn0CjUgOXtPCJKnKLqA.jpg" /></p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LeakyReLU</span>:</span>
    <span class="hljs-string">"""Applies the element-wise function:
    Args:
        - alpha: Negative slope value: controls the angle of the negative slope in the :math:`-x` direction. Default: ``1e-2``
    """</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, alpha=<span class="hljs-number">0.2</span></span>):</span>
        self.alpha = alpha

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-keyword">return</span> np.where(x &gt;= <span class="hljs-number">0</span>, x, self.alpha * x)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">gradient</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-string">"""
        Computes Gradient of LeakyReLU
            Args:
                x: input tensor
            Returns:
                Gradient of X
        """</span>
        <span class="hljs-keyword">return</span> np.where(x &gt;= <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, self.alpha)
</code></pre>
<h2 id="tanh-or-hyperbolic-tangent-activation"><code>tanH</code> or hyperbolic tangent activation</h2>
<p>The sigmoid maps the output between 0-1 but here <code>tanH</code> maps the output to -1 and 1. The advantage is that the negative inputs will be mapped strongly negative and the zero inputs will be mapped near zero in the tanh graph.</p>
<p>The function is differentiable. And the function is monotonic while its derivative is not monotonic. The <code>tanH</code> function is mainly used classification between two classes.</p>
<p>Let's implement this in code</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TanH</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-number">2</span> / (<span class="hljs-number">1</span> + np.exp(<span class="hljs-number">-2</span> * x)) - <span class="hljs-number">1</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">gradient</span>(<span class="hljs-params">self, x</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span> - np.power(self.__call__(x), <span class="hljs-number">2</span>)
</code></pre>
<h2 id="softmax">Softmax</h2>
<p>Softmax loss is used when multi-class classifications are performed. So here is the code:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Softmax</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">self, x</span>):</span>
        e_x = np.exp(x - np.max(x, axis=<span class="hljs-number">-1</span>, keepdims=<span class="hljs-literal">True</span>))
        <span class="hljs-keyword">return</span> e_x / np.sum(e_x, axis=<span class="hljs-number">-1</span>, keepdims=<span class="hljs-literal">True</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">gradient</span>(<span class="hljs-params">self, x</span>):</span>
        p = self.__call__(x)
        <span class="hljs-keyword">return</span> p * (<span class="hljs-number">1</span> - p)
</code></pre>
]]></content:encoded></item><item><title><![CDATA[What is PyTorch .detach() method?]]></title><description><![CDATA[What is PyTorch .detach() method?
PyTorch's detach method works on the tensor class. 
tensor.detach() creates a tensor that shares storage with tensor that does not require gradient. tensor.clone() creates a copy of tensor that imitates the original ...]]></description><link>https://publications.theroyakash.com/pytorch-detach</link><guid isPermaLink="true">https://publications.theroyakash.com/pytorch-detach</guid><category><![CDATA[Python 3]]></category><category><![CDATA[pytorch]]></category><category><![CDATA[Deep Learning]]></category><category><![CDATA[Machine Learning]]></category><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Thu, 22 Oct 2020 15:25:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1604350296849/WrX7XXu5v.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>What is PyTorch <code>.detach()</code> method?</p>
<p>PyTorch's detach method works on the tensor class. </p>
<p><code>tensor.detach()</code> creates a tensor that shares storage with tensor that does not require gradient. <code>tensor.clone()</code> creates a copy of tensor that imitates the original tensor's <code>requires_grad</code> field.</p>
<p>You should use <code>detach()</code> when attempting to remove a tensor from a computation graph, and clone as a way to copy the tensor while still keeping the copy as a part of the computation graph it came from.</p>
<p>Let's see that in an example here</p>
<pre><code class="lang-python">X = torch.ones((<span class="hljs-number">28</span>, <span class="hljs-number">28</span>), dtype=torch.float32, requires_grad=<span class="hljs-literal">True</span>)
y = X**<span class="hljs-number">2</span>
z = X**<span class="hljs-number">2</span>

result = (y+z).sum()

torchviz.make_dot(result).render(<span class="hljs-string">'Attached'</span>, format=<span class="hljs-string">'png'</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603379723625/NmP78Zuam.png" alt="1.png" /></p>
<p>And now one with the detach.</p>
<pre><code class="lang-python">X = torch.ones((<span class="hljs-number">28</span>, <span class="hljs-number">28</span>), dtype=torch.float32, requires_grad=<span class="hljs-literal">True</span>)
y = X**<span class="hljs-number">2</span>
z = X.detach()**<span class="hljs-number">2</span>

result = (y+z).sum()

torchviz.make_dot(result).render(<span class="hljs-string">'Attached'</span>, format=<span class="hljs-string">'png'</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603379927351/ZsGdLEa2U.png" alt="Screen Shot 2020-10-22 at 8.48.43 PM.png" /></p>
<p>As you can see now that the branch of computation with <code>x**2</code> is no longer tracked. This is reflected in the gradient of the result which no longer records the contribution of this branch</p>
]]></content:encoded></item><item><title><![CDATA[Welcome to theroyakash Publication]]></title><description><![CDATA[Welcome to theroyakash publication, here you’ll get the latest in publications from theroyakash on whatever I'm working on. I also have a subreddit for announcement purposes & I have a discord server. Join and connect with me there. Cool researches, ...]]></description><link>https://publications.theroyakash.com/welcome</link><guid isPermaLink="true">https://publications.theroyakash.com/welcome</guid><dc:creator><![CDATA[theroyakash]]></dc:creator><pubDate>Sun, 04 Oct 2020 04:06:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1604350400372/Js2UgXP_K.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1601784099288/LfqOJ9PVQ.png" alt="image.png" /></p>
<p>Welcome to theroyakash publication, here you’ll get the latest in publications from theroyakash on whatever I'm working on. I also have a subreddit for announcement purposes &amp; I have a discord server. Join and connect with me there. Cool researches, projects and other things coming very soon.</p>
<p>Computer scientist theroyakash researches computer vision and artificial intelligence. This is the publications from theroyakash.</p>
<ul>
<li>Announcement subreddit:  <a target="_blank" href="https://www.reddit.com/r/theroyakash/">r/theroyakash</a> </li>
<li>Join our discord server  <a target="_blank" href="https://discord.com/invite/ENGf4nr">here</a>.</li>
</ul>
]]></content:encoded></item></channel></rss>