<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Neeraj Sujan, Author at Be on the Right Side of Change</title>
	<atom:link href="https://blog.finxter.com/author/neerajsujan/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.finxter.com/author/neerajsujan/</link>
	<description></description>
	<lastBuildDate>Fri, 16 Sep 2022 09:12:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.3</generator>

<image>
	<url>https://blog.finxter.com/wp-content/uploads/2020/08/cropped-cropped-finxter_nobackground-32x32.png</url>
	<title>Neeraj Sujan, Author at Be on the Right Side of Change</title>
	<link>https://blog.finxter.com/author/neerajsujan/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>[Floyd&#8217;s Algorithm] How to Detect a Cycle in a Linked List in Python?</title>
		<link>https://blog.finxter.com/how-to-detect-a-cycle-in-a-linked-list-in-python/</link>
		
		<dc:creator><![CDATA[Neeraj Sujan]]></dc:creator>
		<pubDate>Mon, 03 May 2021 11:53:51 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python List]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=29319</guid>

					<description><![CDATA[<p>In this tutorial you will learn how to implement a simple Python program to detect if a linked list consists of a cycle or not. If you need a brief refresher on linked lists, do check out this blog post.  Definition of a Cycle in a Linked List A linked list can consist of a ... <a title="[Floyd&#8217;s Algorithm] How to Detect a Cycle in a Linked List in Python?" class="read-more" href="https://blog.finxter.com/how-to-detect-a-cycle-in-a-linked-list-in-python/" aria-label="Read more about [Floyd&#8217;s Algorithm] How to Detect a Cycle in a Linked List in Python?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-detect-a-cycle-in-a-linked-list-in-python/">[Floyd&#8217;s Algorithm] How to Detect a Cycle in a Linked List in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this tutorial you will learn how to implement a simple Python program to detect if a linked list consists of a cycle or not. If you need a brief refresher on linked lists, do check out this blog <a href="https://blog.finxter.com/linked-lists-in-python/" target="_blank" rel="noreferrer noopener">post</a>. </p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="[Floyd&#039;s Algorithm] How to Detect a Cycle in a Linked List in Python?" width="937" height="527" src="https://www.youtube.com/embed/x6DFcncz8Tk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Definition of a Cycle in a Linked List</h2>



<p class="wp-block-paragraph">A linked list can consist of a cycle if a tail node of the linked list points to another node in the list. Let us see a small example to understand the concept of cycle in a linked list.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://docs.google.com/drawings/u/0/d/slK2Szhi1prlv2Ck-u5M9og/image?w=624&amp;h=100&amp;rev=47&amp;ac=1&amp;parent=1EQsjGF10eTeF7E0_0u0h-NkP1Y-jm79KZVcwT3gy8YA" alt="Definition of a Cycle in a Linked List"/><figcaption>Fig 1: Cycle in a linked list</figcaption></figure></div>



<p class="wp-block-paragraph">In the above figure, you can see that the tail node of the linked list, instead of pointing to NULL, points to another node &#8212; the second node in the list. If such a scenario arises, we say there is a cycle or a loop in a list.</p>



<h2 class="wp-block-heading">Initialization and Setup</h2>



<p class="wp-block-paragraph">We will first begin by initializing the nodes and constructing the linked list.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from linked_list import Node, LinkedList
 
node1 =  Node(5)
node2 =  Node(6)
node3 =  Node(7)
node4 =  Node(8)
node5 =  Node(9)
 
 
ll = LinkedList()
 
ll.insert_back(node1)
ll.insert_back(node2)
ll.insert_back(node3)
ll.insert_back(node4)
ll.insert_back(node5)
</pre>



<p class="wp-block-paragraph">Now, we will connect the fifth node to the 3rd node forming a cycle.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">node5.next = node3</pre>



<h2 class="wp-block-heading">Approach 1: Naive Approach</h2>



<p class="wp-block-paragraph">We will now look at a simple approach to implement the logic to find out if the list consists of a cycle or not. One approach would be to store the address of the node in a dictionary as we traverse through the list and as soon as we come across a node whose address was already in the dictionary, we can say that there was a cycle in the list. Let us see how we can implement this in Python</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""> 
addresses = {}
temp_node = node1
while (temp_node):
   address = id(temp_node)
   print(address)
   if address not in addresses:
       addresses[address] = 1
   else:
       print('cycle in a linked list')
       print(temp_node.data)
       break
   temp_node = temp_node.next
</pre>



<p class="wp-block-paragraph">The disadvantage of the previous approach is that it takes 0(n) space complexity. Can we solve this problem in O(1) space complexity?</p>



<h2 class="wp-block-heading">Approach 2:  Floyd’s Cycle Detection Algorithm </h2>



<p class="wp-block-paragraph">We can solve this problem by initializing two pointers, a slow pointer, and a fast pointer. On every iteration, we increment the slow pointer by 1 and the fast pointer by 2. We then check if the slow pointer is equal to the fast pointer i.e. do both the pointers point to the same node. If that is the case, we can say that there is a cycle or a loop in a linked list. Once we find the cycle we can break out of the <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">while loop</a>. </p>



<p class="wp-block-paragraph"><strong>Demonstration</strong></p>



<p class="wp-block-paragraph">Let us imagine we have a list with 5 nodes as illustrated in the figure below. As you can see the tail node i.e. the node with a value of 9 is pointing to the node with the value 7 or the 3rd node in the list, thereby forming a loop or a cycle.</p>



<figure class="wp-block-image"><img decoding="async" src="https://docs.google.com/drawings/u/0/d/sD3VoRdPz1gQ0FuMgCvUYjA/image?w=624&amp;h=103&amp;rev=4&amp;ac=1&amp;parent=1EQsjGF10eTeF7E0_0u0h-NkP1Y-jm79KZVcwT3gy8YA" alt=""/></figure>



<p class="wp-block-paragraph"><strong>Iteration 1:&nbsp;&nbsp;</strong></p>



<p class="wp-block-paragraph">In the first iteration, the slow pointer is incremented by 1 and the fast pointer by 2. As you can see in the figure below, the slow pointer is now pointing to the node with the value 6 and the fast pointer is pointing to the node with the value 7.</p>



<figure class="wp-block-image"><img decoding="async" src="https://docs.google.com/drawings/u/0/d/sXTIXTOmKz8UUI9EIAH3u4g/image?w=624&amp;h=107&amp;rev=59&amp;ac=1&amp;parent=1EQsjGF10eTeF7E0_0u0h-NkP1Y-jm79KZVcwT3gy8YA" alt=""/></figure>



<p class="wp-block-paragraph"><strong>Iteration 2:</strong></p>



<p class="wp-block-paragraph">In the second iteration&nbsp; the slow pointer points to the node with the value 7 and the fast pointer points to the node with the value 9 or the last node.</p>



<figure class="wp-block-image"><img decoding="async" src="https://docs.google.com/drawings/u/0/d/s-kjSuuDFb1tdHMCPohs1cg/image?w=624&amp;h=103&amp;rev=11&amp;ac=1&amp;parent=1EQsjGF10eTeF7E0_0u0h-NkP1Y-jm79KZVcwT3gy8YA" alt=""/></figure>



<p class="wp-block-paragraph"><strong>Iteration 3:</strong></p>



<p class="wp-block-paragraph">In the third iteration we observe that both the slow and fast pointers are pointing to the same&nbsp; node i.e. the node with the value 8. In this case, we can conclude that there is a cycle in a list.</p>



<figure class="wp-block-image"><img decoding="async" src="https://docs.google.com/drawings/u/0/d/s8i4b1A-OMF4rInjXeIIY7A/image?w=624&amp;h=124&amp;rev=5&amp;ac=1&amp;parent=1EQsjGF10eTeF7E0_0u0h-NkP1Y-jm79KZVcwT3gy8YA" alt=""/></figure>



<p class="wp-block-paragraph">Let us know see how we can implement the adobe logic in Python.&nbsp;</p>



<p class="wp-block-paragraph">We first initialize the slow pointer and the fast pointer pointing to the head node or the first node. We then run a while loop, and we run the loop as long as the slow pointer is valid, the fast pointer is valid and the next value of the fast pointer is valid. We then keep incrementing the slow and fast pointers by 1 and 2 respectively and if both the pointers have the same address value, we break out of the loop and print that there was a cycle in a linked list. You can find the entire logic below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">slow_ptr = node1
fast_ptr = node1
 
while (slow_ptr and fast_ptr and fast_ptr.next):
   slow_ptr = slow_ptr.next
   fast_ptr = fast_ptr.next.next
   if slow_ptr == fast_ptr:
       print('loop in a linked list', slow_ptr.data)
       break
   else:
       print(slow_ptr.data, fast_ptr.data)</pre>



<p class="wp-block-paragraph">This algorithm is also called the <strong><em>Floyd’s cycle detection algorithm</em></strong>.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">In this tutorial, we saw how we can detect a cycle in a loop using the Floyd’s cycle detection algorithm. This algorithm can detect a loop in <strong><em>O(1)</em></strong> space complexity and <strong><em>O(n)</em></strong> time complexity.</p>
<p>The post <a href="https://blog.finxter.com/how-to-detect-a-cycle-in-a-linked-list-in-python/">[Floyd&#8217;s Algorithm] How to Detect a Cycle in a Linked List in Python?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Ignore Exceptions the Pythonic Way?</title>
		<link>https://blog.finxter.com/how-to-ignore-exceptions-the-pythonic-way/</link>
		
		<dc:creator><![CDATA[Neeraj Sujan]]></dc:creator>
		<pubDate>Mon, 12 Apr 2021 15:12:03 +0000</pubDate>
				<category><![CDATA[Exception Handling]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=27950</guid>

					<description><![CDATA[<p>If you are an application developer, you might have to implement an error-free code that is well tested. In my instances, we would like to ignore I/O or Numerical exceptions. In this blog post, you will learn how we can safely ignore exceptions in Python. Imagine you are working on an application&#160; where you have ... <a title="How to Ignore Exceptions the Pythonic Way?" class="read-more" href="https://blog.finxter.com/how-to-ignore-exceptions-the-pythonic-way/" aria-label="Read more about How to Ignore Exceptions the Pythonic Way?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-ignore-exceptions-the-pythonic-way/">How to Ignore Exceptions the Pythonic Way?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">If you are an application developer, you might have to implement an error-free code that is well tested. In my instances, we would like to ignore I/O or Numerical exceptions. In this blog post, you will learn how we can safely ignore exceptions in Python.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="How to Properly Ignore Exceptions in Python?" width="937" height="527" src="https://www.youtube.com/embed/73kfLd0E4Dw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="wp-block-paragraph">Imagine you are working on an application&nbsp; where you have a list of numbers and would like to output the reciprocal of the numbers. If by mistake the list consists of 0, then the program would crash since we are diving 1 by 0 which will raise an exception. We can implement this in a bug free manner by using a try and except block.</p>



<p class="wp-block-paragraph">We can achieve this by the following two steps</p>



<ol class="wp-block-list"><li>Put the logic of taking the reciprocal of the number in try block</li><li>Implement an exception block that is executed wherever the number is 0. Continue with the rest of the logic </li></ol>



<h2 class="wp-block-heading">Without a try-except Block</h2>



<p class="wp-block-paragraph">Let us first implement the logic using a simple for <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">loop</a>. As you can see in the output below, the program crashed when the number was 0</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [12, 1, 0, 45, 56]
for number in numbers:
    print('result is {}'.format(1/number))</pre>



<p class="wp-block-paragraph">Output</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">result is 0.08333333333333333
result is 1.0

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
&lt;ipython-input-27-c1f2d047aa92> in &lt;module>()
      1 for number in numbers:
----> 2   print('result is {}'.format(1/number))

ZeroDivisionError: division by zero
﻿</pre>



<h2 class="wp-block-heading">With a try-except Block</h2>



<p class="wp-block-paragraph">Let us now see how we can safely ignore an exception</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">numbers = [12,1,0,45,56]
for number in numbers:
    try:
        print('result is {}'.format(1/number))
    except Exception as e:
        print('Ignoring Exception', e)</pre>



<p class="wp-block-paragraph">Output</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">result is 0.08333333333333333
result is 1.0
Ignoring Exception division by zero
result is 0.022222222222222223
result is 0.017857142857142856</pre>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this blog post you learned how to safely ignore exceptions in Python. You learnt how to use a try and except block and continue with the program if an exception is encountered.</p>
<p>The post <a href="https://blog.finxter.com/how-to-ignore-exceptions-the-pythonic-way/">How to Ignore Exceptions the Pythonic Way?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Set the y-Axis Limit in Python Matplotlib</title>
		<link>https://blog.finxter.com/how-to-set-the-y-axis-limit-in-python-matplotlib/</link>
		
		<dc:creator><![CDATA[Neeraj Sujan]]></dc:creator>
		<pubDate>Mon, 12 Apr 2021 15:00:52 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Matplotlib]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=27945</guid>

					<description><![CDATA[<p>If you work in the field of data science you might have to draw a lot of plots using either Matplotlib or Seaborn. In this blog post, you will learn how to set a limit to the y-axis values in Matplotlib. We will start by loading the Boston household data and process the data to ... <a title="How to Set the y-Axis Limit in Python Matplotlib" class="read-more" href="https://blog.finxter.com/how-to-set-the-y-axis-limit-in-python-matplotlib/" aria-label="Read more about How to Set the y-Axis Limit in Python Matplotlib">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-set-the-y-axis-limit-in-python-matplotlib/">How to Set the y-Axis Limit in Python Matplotlib</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">If you work in the field of data science you might have to draw a lot of plots using either <a href="https://blog.finxter.com/matplotlib-full-guide/" title="Matplotlib — A Simple Guide with Videos" target="_blank" rel="noreferrer noopener">Matplotlib </a>or <a href="https://blog.finxter.com/heatmaps-with-seaborn/" title="Creating Beautiful Heatmaps with Seaborn" target="_blank" rel="noreferrer noopener">Seaborn</a>. In this blog post, you will learn how to set a limit to the y-axis values in Matplotlib.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="How to Set the y-Axis Limit in Python Matplotlib" width="937" height="527" src="https://www.youtube.com/embed/rEO5TpGrKDs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="wp-block-paragraph">We will start by loading the <em>Boston household data</em> and process the data to visualize the <em>median price of the house</em>.</p>



<ol class="wp-block-list"><li><strong>Load the data</strong></li><li><strong>Import Libraries and plot data points</strong></li><li><strong>Set the y-axis limit</strong></li></ol>



<h2 class="wp-block-heading">Load the data</h2>



<p class="wp-block-paragraph">Let us begin by loading the data using the <a href="https://blog.finxter.com/pandas-quickstart/" title="10 Minutes to Pandas (in 5 Minutes)" target="_blank" rel="noreferrer noopener">pandas </a>library</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('sample_data/california_housing_test.csv')</pre>



<h2 class="wp-block-heading">Import Libraries and Plot Data Points</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">house_values = data['median_house_value'].values
house_values = sorted(house_values)</pre>



<p class="wp-block-paragraph">We now have extracted the <code>median_hoise_value</code> column and sorted the values in ascending order. Let us now being plotting the data</p>



<h2 class="wp-block-heading">Set the y-axis Limit</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">paramValues = range(len(house_values))
plt.figure(figsize=(8.5,11))
plt.plot(paramValues,house_values)
plt.title('Median house price')
plt.ylabel('Median Price')
plt.xlabel('Range')
plt.grid(True)
plt.show()</pre>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh3.googleusercontent.com/b1R_AZyhCiAkDkdM13-Gc6BhY01gzzDMzU1XNq9BSCIJgdN2HKqQ7mBEuhJNKTBB_AkUuPn4b0qoN7T3dgZaA7dooNlavn5w-tPdlJiSBKKVi36BWNsfXSVNC-v9kKh-7Mua0b-v" alt=""/></figure></div>



<h2 class="wp-block-heading"><strong>Change y-axis Limit</strong></h2>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">paramValues = range(len(house_values))
plt.figure(figsize=(8.5,11))
plt.plot(paramValues,house_values)
plt.title('Median house price')
plt.ylabel('Median Price')
plt.xlabel('Range')
plt.grid(True)
plt.ylim((None,400000))
plt.show()</pre>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://lh3.googleusercontent.com/26p9TjycbPKkLmvdX9iLIvSOJ-f9KFJDUXpZl7e8rl4XYJHyE0wi_AKcxlP7ugBMqHlh6tZW_Q0Jl4PGoS0Aput7aJ6FrgkvNy2_EdOCaf6VkypNVTGfuR9UF_zbI0cBa4OX20S4" alt=""/></figure></div>



<p class="wp-block-paragraph">By using the <code>plt.ylim()</code> function we can change the limit of the y-axis. In the above example setting the second parameter to 400000 we have to change the maximum value of the y axis. Similarly, we can change the minimum value of the y-axis by changing the first argument in the <code>plt.ylim()</code> function</p>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this blog post you have learned how to set the y-axis limit in <code>matpltotlib</code>.  I hope you found the post informative.</p>
<p>The post <a href="https://blog.finxter.com/how-to-set-the-y-axis-limit-in-python-matplotlib/">How to Set the y-Axis Limit in Python Matplotlib</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Get A Value From a Cell in a Pandas DataFrame</title>
		<link>https://blog.finxter.com/how-to-get-a-value-from-a-cell-of-a-pandas-dataframe/</link>
		
		<dc:creator><![CDATA[Neeraj Sujan]]></dc:creator>
		<pubDate>Mon, 12 Apr 2021 14:35:07 +0000</pubDate>
				<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Pandas Library]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=27936</guid>

					<description><![CDATA[<p>If you are a data analyst or work with a lot of data, you might have come across the Pandas library for data manipulation. In this tutorial, we will examine how we can get a value of a cell from a Pandas DataFrame. Related Tutorial: 5 Minutes to Pandas There are 5 ways to extract ... <a title="How to Get A Value From a Cell in a Pandas DataFrame" class="read-more" href="https://blog.finxter.com/how-to-get-a-value-from-a-cell-of-a-pandas-dataframe/" aria-label="Read more about How to Get A Value From a Cell in a Pandas DataFrame">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-get-a-value-from-a-cell-of-a-pandas-dataframe/">How to Get A Value From a Cell in a Pandas DataFrame</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">If you are a data analyst or work with a lot of data, you might have come across the <a href="https://blog.finxter.com/pandas-cheat-sheets/" title="[PDF Collection] 7 Beautiful Pandas Cheat Sheets — Post Them to Your Wall" target="_blank" rel="noreferrer noopener">Pandas library</a> for data manipulation. In this tutorial, we will examine how we can get a value of a cell from a Pandas <a href="https://blog.finxter.com/how-to-create-a-dataframe-in-pandas/" title="How to Create a DataFrame in Pandas?" target="_blank" rel="noreferrer noopener">DataFrame</a>. </p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Get A Value From a Cell of a Pandas DataFrame" width="937" height="527" src="https://www.youtube.com/embed/q0hMnRKZ3uc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="wp-block-paragraph"><strong>Related Tutorial:</strong> <a href="https://blog.finxter.com/pandas-quickstart/" target="_blank" rel="noreferrer noopener" title="10 Minutes to Pandas (in 5 Minutes)">5 Minutes to Pandas</a></p>



<p class="wp-block-paragraph">There are <strong>5 ways to extract value from a cell of a Pandas DataFrame</strong></p>



<ol class="wp-block-list"><li><strong>Extract data using </strong><code><strong>iloc</strong></code><strong> or indexing</strong></li><li><strong>Extract data using </strong><code><strong>iat</strong></code></li><li><strong>Extract data using </strong><code><strong>loc</strong></code></li><li><strong>Extract data using </strong><code><strong>at</strong></code></li><li><strong>Extract data using </strong><code><strong>data_frame.values[]</strong></code></li></ol>



<h2 class="wp-block-heading">Loading the Dataset</h2>



<p class="wp-block-paragraph">We will examining the above methods by loading a sample dataset. I have used the California housing dataset that you can download from this <a href="https://www.kaggle.com/camnugent/california-housing-prices" target="_blank" rel="noreferrer noopener">link</a>.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd
data = pd.read_csv('sample_data/california_housing_test.csv')</pre>



<p class="wp-block-paragraph">Let us see the columns of the dataset</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data.head(5)</pre>



<p class="wp-block-paragraph">Output</p>



<p class="wp-block-paragraph">We can see the first 5 rows of the dataset. The dataset has 9 columns. We will now examine the 5 different methods to extract the 2nd row value of the latitude column&nbsp;</p>



<figure class="wp-block-image"><img decoding="async" src="https://lh6.googleusercontent.com/9fuDRS3Qabw0qpvnis7uZxKp79mHaCAtV-8NGLS1FxjKhNyPHaEo4jf1VfBeDtRRNg1X221KUwt0zr-v7HFbh48-u_HWxiMN-LLduofGgZuMZrjwD5YDuy5QiH_80fMIHac-xQRD" alt=""/></figure>



<h2 class="wp-block-heading">Method 1: Extract Data using iloc or Indexing</h2>



<p class="wp-block-paragraph">We can use normal indexing the extract the value.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data.iloc[1]['latitude']</pre>



<p class="wp-block-paragraph">Since the indexing starts from 0, the 1st index is used to get the contents for the 2nd row. Once we extract the row, we can extract any column value that we want. In our case we wanted to get the latitude value. We get the following output.</p>



<p class="wp-block-paragraph"><strong>Output</strong></p>



<figure class="wp-block-table"><table><tbody><tr><td>34.26</td></tr></tbody></table></figure>



<h2 class="wp-block-heading">Method 2: <strong>Extract Data using iat</strong></h2>



<p class="wp-block-paragraph">We will not look at another method to extract the latitude value from the 2nd row.</p>



<p class="wp-block-paragraph">We can call the <code>iat</code> method of the pandas dataframe to get the cell value. The <code>iat</code> value is called using the row index and column index as an argument. In our example latitude is the 1st column index and for the 2nd row we will use the 1st&nbsp;Index.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data.iat[1,1]</pre>



<p class="wp-block-paragraph">&nbsp;&nbsp;&nbsp;&nbsp; <strong>Output</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">34.26</pre>



<h2 class="wp-block-heading">Method 3: <strong>Extract Data using loc</strong></h2>



<p class="wp-block-paragraph">We can use the loc method to get the value. The loc method unlike the ioc method can be used by passing in a string as an argument if the index values are strings. In our example since all indexes are numerical values, we can do the following</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data.loc[1]['latitude']</pre>



<p class="wp-block-paragraph"><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</strong>&nbsp;<strong>Output</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">34.26</pre>



<h2 class="wp-block-heading">Method 4: <strong>Extract Data using at</strong></h2>



<p class="wp-block-paragraph">The fourth way to extract a value from the cell is using the <code>at</code> method. The <code>at</code> method takes in the row index as an argument and the column name as the second argument.&nbsp;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data.at[1,'latitude']</pre>



<p class="wp-block-paragraph"><strong>&nbsp;&nbsp;</strong>&nbsp;<strong>Output</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">34.26</pre>



<h2 class="wp-block-heading">Method 5: Extract Data using data_frame.values[]</h2>



<p class="wp-block-paragraph">The last method to extract the value from a specific cell is to first convert the frame into a series by using the column name we are interested in getting the value from and then converting the series into a list using the values property. We can then use normal row indexing to get the value from a specific row.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">data['latitude'].values[1]</pre>



<p class="wp-block-paragraph">&nbsp;<strong>Output</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">34.26</pre>



<p class="has-base-background-color has-background wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f449.png" alt="👉" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Recommended Tutorial</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/python-find-longest-string-in-a-dataframe-column/" data-type="post" data-id="682285" target="_blank">Python Find Longest String in a DataFrame Column</a></p>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this blog post, we saw 5 methods to extract the value from a pandas dataframe. Depending on the use case, we can use any of the above 5 methods to get a value from a cell.</p>



<h2 class="wp-block-heading">Programming Humor</h2>



<p class="has-global-color-8-background-color has-background wp-block-paragraph"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4a1.png" alt="💡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science.</p>



<p class="wp-block-paragraph">~~~</p>



<ul class="has-global-color-8-background-color has-background wp-block-list"><li><strong>Question</strong>: Why do Java programmers wear glasses?</li><li><strong>Answer</strong>: Because they cannot C# &#8230;!</li></ul>



<p class="wp-block-paragraph">Feel free to check out <a href="https://blog.finxter.com/what-is-the-geekiest-joke/" data-type="post" data-id="617" target="_blank" rel="noreferrer noopener">our blog article</a> with more coding jokes. <img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<p>The post <a href="https://blog.finxter.com/how-to-get-a-value-from-a-cell-of-a-pandas-dataframe/">How to Get A Value From a Cell in a Pandas DataFrame</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Change the Working Directory in Python</title>
		<link>https://blog.finxter.com/how-to-change-the-working-directory-in-python/</link>
		
		<dc:creator><![CDATA[Neeraj Sujan]]></dc:creator>
		<pubDate>Mon, 12 Apr 2021 14:19:06 +0000</pubDate>
				<category><![CDATA[Operating System]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=27922</guid>

					<description><![CDATA[<p>If you have worked on a Python application where you had data in another folder, you would have used a command-line tool like cd to change directories. In this tutorial, we will learn a more Pythonic way of changing directories. Changing directories using the os.chdir function The easiest way to change the working directory in ... <a title="How to Change the Working Directory in Python" class="read-more" href="https://blog.finxter.com/how-to-change-the-working-directory-in-python/" aria-label="Read more about How to Change the Working Directory in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-change-the-working-directory-in-python/">How to Change the Working Directory in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">If you have worked on a Python application where you had data in another folder, you would have used a command-line tool like <code>cd</code> to change directories. In this tutorial, we will learn a more Pythonic way of changing directories.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Change the Working Directory in Python" width="937" height="527" src="https://www.youtube.com/embed/82W0RWsNQWI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Changing directories using the os.chdir function</h2>



<p class="wp-block-paragraph">The easiest way to change the working directory in Python is importing the <a href="https://blog.finxter.com/exploring-pythons-os-module/" target="_blank" rel="noreferrer noopener" title="Exploring Python’s OS Module"><code>os</code> package</a> and calling the <code>chdir()</code> function. The function takes in the target directory as an input parameter</p>



<p class="wp-block-paragraph">Let us see an example</p>



<ol class="wp-block-list"><li><strong>Get the current working directory</strong></li></ol>



<p class="wp-block-paragraph">Let us first see the current working directory in Python. We can achieve this by calling the <code>os.getcwd()</code> function</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
os.getcwd()</pre>



<p class="wp-block-paragraph">We get the following output when we execute the above two lines</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/content</pre>



<ol class="wp-block-list" start="2"><li><strong>Get the contents of the current working directory</strong></li></ol>



<p class="wp-block-paragraph"><strong> </strong>We will now execute the function call to get the contents of the working directory. We can do this by calling the following function in Python</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">os.listdir()</pre>



<p class="wp-block-paragraph">We get the following output</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">['.config', 'sample_data']</pre>



<ol class="wp-block-list" start="3"><li><strong>Navigate to target directory</strong></li></ol>



<p class="wp-block-paragraph"><strong>&nbsp;&nbsp;&nbsp;&nbsp;</strong>We will now use the <code>os.chdir()</code> function to navigate to the <code>‘sample_data’</code> directory</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">os.chdir('sample_data')</pre>



<p class="wp-block-paragraph">&nbsp;&nbsp;We can now again call the <code>os.getcwd()</code> function to verify if the directory was changed.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">os.chdir('sample_data')</pre>



<p class="wp-block-paragraph">&nbsp;&nbsp;We get the following output</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/content/sample_data   </pre>



<h2 class="wp-block-heading">Changing&nbsp;the Working Directory using Context Manager</h2>



<p class="wp-block-paragraph">The second approach to change the working directory is using a context manager. Let us see an example and the benefits of using a context manager.</p>



<p class="wp-block-paragraph">In the previous example, the working directory changes even outside a function. Most of the time, we would want to run out logic inside a function and once we exit the function, we would like to return the previous working directory. A context manager helps us to achieve this without any errors</p>



<ol class="wp-block-list"><li><strong>Import the libraries</strong></li></ol>



<p class="wp-block-paragraph">Let us first import the libraries</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from contextlib import contextmanager
import os</pre>



<ol class="wp-block-list" start="2"><li><strong>Function to change directories</strong></li></ol>



<p class="wp-block-paragraph">We will now implement a function call <code>change_path()</code> using the <code>@contextmanager</code> <a href="https://blog.finxter.com/closures-and-decorators-in-python/" target="_blank" rel="noreferrer noopener" title="Closures and Decorators in Python">decorator function</a>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@contextmanager
def change_path(newdir):
    old_path = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(old_path)
﻿</pre>



<ol class="wp-block-list" start="3"><li><strong>Call the function change_path</strong></li></ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">with change_path('sample_data'):
    print(os.getcwd())</pre>



<p class="wp-block-paragraph">We get the following output</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/content/sample_data</pre>



<p class="wp-block-paragraph">If we now call the <code>os.getcwd()</code> we get the following output</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">/content</pre>



<p class="wp-block-paragraph">As you can see outside the context of change_path we are in the previous directory. We can do the processing by changing the directory inside the context of the change_path function</p>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this tutorial we looked at two ways to change the working directory in Python.</p>



<ol class="wp-block-list"><li>Using <code>getcwd()</code> we can change the directory, but the directory is changed also outside the scope of a function</li><li>Using <code>contextmanager</code> we can change the directory in an error-free manner and outside the context of a function, the directory is not changed.</li></ol>



<p>The post <a href="https://blog.finxter.com/how-to-change-the-working-directory-in-python/">How to Change the Working Directory in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Run TensorFlow in a Jupyter Notebook?</title>
		<link>https://blog.finxter.com/how-to-run-tensorflow-in-a-jupyter-notebook/</link>
		
		<dc:creator><![CDATA[Neeraj Sujan]]></dc:creator>
		<pubDate>Mon, 05 Apr 2021 14:14:48 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Artificial Intelligence]]></category>
		<category><![CDATA[Jupyter]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[TensorFlow]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=27458</guid>

					<description><![CDATA[<p>If you are a machine learning practitioner you might have come across the TensorFlow library. TensorFlow is a popular machine learning library and finds its use in a lot of AI and machine learning applications. In this tutorial you will learn How to install TensorFlow in a virtual environment How to activate your environment in ... <a title="How to Run TensorFlow in a Jupyter Notebook?" class="read-more" href="https://blog.finxter.com/how-to-run-tensorflow-in-a-jupyter-notebook/" aria-label="Read more about How to Run TensorFlow in a Jupyter Notebook?">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/how-to-run-tensorflow-in-a-jupyter-notebook/">How to Run TensorFlow in a Jupyter Notebook?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">If you are a machine learning practitioner you might have come across the TensorFlow library. TensorFlow is a popular machine learning library and finds its use in a lot of AI and machine learning applications. In this tutorial you will learn</p>



<ol class="wp-block-list"><li>How to install TensorFlow in a virtual environment</li><li>How to activate your environment in Jupyter Notebook</li><li>How to use TensorFlow in a Jupyter Notebook</li></ol>



<h2 class="wp-block-heading">How to install TensorFlow in a virtual environment</h2>



<p class="wp-block-paragraph">In order to use TensorFlow in a Juypter notebook, we need to create an independent environment to manage our dependencies. We will begin by creating an anaconda environment. We first begin by creating a directory with an environments.yml file and a notebooks directory. We will use the <code>notebooks</code> directory to create our notebook for TensorFlow experiments. The <code>environments.yml</code> file is used to manage our dependencies</p>



<p class="wp-block-paragraph">As a next step, you can open a text-editor of your choice and add the following line in your <code>environments.yml</code> file</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">name: tensorflow-development
channels:
- anaconda
- conda-forge
- defaults
 
dependencies:
 - python=3.7
 - numpy
 - matplotlib
 - pandas
 - tensorflow
 - notebook
 - nb_conda_kernels
 - jupyter_contrib_nbextensions</pre>



<p class="wp-block-paragraph">We will now create a new environment called <code>tensorflow-development</code> using the following command in your terminal:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">conda env create -f environment.yml</pre>



<figure class="wp-block-image"><img decoding="async" src="https://lh5.googleusercontent.com/wKQD3MCJlhdrOV0bbtlktXeywdbR9GLa3gwg9MpVa4YEAYXtz9dJPoCTEtBFwr-TM26vp4YdhqchMn3dv4M-jGVuxGzL7jlpbXXkzzeW0OZP0MI8AW-KgRDkfzFDOPrvRWtSMZGB" alt=""/></figure>



<h2 class="wp-block-heading">How to activate your environment in Jupyter Notebook</h2>



<p class="wp-block-paragraph">Once you have created your environment let us now see how we can activate our environment</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">conda activate tensorflow-development</pre>



<h2 class="wp-block-heading">How to use TensorFlow in a Jupyter Notebook</h2>



<p class="wp-block-paragraph">We will now execute the following command to start the Jupyter notebook</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">jupyter notebook</pre>



<p class="wp-block-paragraph">We can now choose the environment which we created and start the Jupyter notebook</p>



<figure class="wp-block-image"><img decoding="async" src="https://lh5.googleusercontent.com/q5ce2rEuQOTh_Uuo6hv-6sfGd6-GF-KE0WWIjlm44yg5juOWRexSsmjETZ0InOHHTUTLuI7cCBrL_5a3uSb51rnUoaZ32nAKVDpIatp39ZsrpM16wNK_SXlOp0y93hr5K8kJWQL2" alt=""/></figure>



<p class="wp-block-paragraph">We can now navigate to <code>notebooks/</code> and create our notebook. We will test to see if TensorFlow was installed successfully. We will import the TensorFlow library and print the version number of the library.</p>



<figure class="wp-block-image"><img decoding="async" src="https://lh5.googleusercontent.com/3To9W-ZT6bMr4hmJm1d69LQyl0cXEy2ZcBaOHma_a68HlSHj5JAF9I4YQ3qXSP_4pjx1QQlNdOf33bWPUaMU2LUuo4WW4zjd0SSAikN4hobWR33U50aTi0l7a0By5EoJhn6oS9DI" alt=""/></figure>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this blog post, we learned how to install the TensorFlow library in a managed python environment. We then had to look at how to use Tensorflow in a Jupyter notebook environment.</p>
<p>The post <a href="https://blog.finxter.com/how-to-run-tensorflow-in-a-jupyter-notebook/">How to Run TensorFlow in a Jupyter Notebook?</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Doubly Linked List in Python</title>
		<link>https://blog.finxter.com/doubly-linked-list-in-python/</link>
		
		<dc:creator><![CDATA[Neeraj Sujan]]></dc:creator>
		<pubDate>Mon, 22 Feb 2021 13:09:24 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python List]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=24301</guid>

					<description><![CDATA[<p>In this tutorial you will learn about doubly linked list. You will learn how to implement a doubly linked list in Python. A doubly linked list, unlike a singly linked lists consists of a data value along with a next and previous pointer. Let us see a simple example of a doubly linked list. In ... <a title="Doubly Linked List in Python" class="read-more" href="https://blog.finxter.com/doubly-linked-list-in-python/" aria-label="Read more about Doubly Linked List in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/doubly-linked-list-in-python/">Doubly Linked List in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this tutorial you will learn about doubly linked list. You will learn how to implement a doubly linked list in Python.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Doubly Linked List in Python" width="937" height="527" src="https://www.youtube.com/embed/VLMZmNUNLkI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p class="wp-block-paragraph">A doubly linked list, unlike a singly linked lists consists of a data value along with a next and previous pointer. Let us see a simple example of a doubly linked list.</p>



<figure class="wp-block-image"><img decoding="async" src="https://docs.google.com/drawings/u/1/d/sDW9BZwbV3K_shZyW8f9ptg/image?w=624&amp;h=169&amp;rev=166&amp;ac=1&amp;parent=1rKUxoYvuvG3BwGazoaYJRM3ZCl29JnHrHpT-QKYDBJM" alt=""/></figure>



<p class="wp-block-paragraph">In the above figure you can visualize a pictorial representation of a doubly linked list. Every node has a pointer to the next node and a pointer to the previous node represented by the next and prev pointer respectively.&nbsp;</p>



<h2 class="wp-block-heading">Operations on a Doubly Linked List</h2>



<p class="wp-block-paragraph">Let us know explore some common operations we can perform on a doubly linked list</p>



<ol class="wp-block-list"><li>Insertion</li><li>Deletion</li><li>Traversal</li></ol>



<p class="wp-block-paragraph">Let us first being by defining a node class which contains the next and previous pointer. Whenever a new node is created the two pointers are set to null initially.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Node(object):
   def __init__(self, value):
       self.data = value
       self.prev = None
       self.next = None
</pre>



<p class="wp-block-paragraph">We began by initializing the constructor of the node class and initializing and declaring the data value, the next pointer and the prev pointer.</p>



<p class="wp-block-paragraph">You can create a node as follows</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">node = Node(12)</pre>



<p class="wp-block-paragraph">This will create a node with the value 12.</p>



<p class="wp-block-paragraph">Let us now begin by defining the doubly linked list and implementing the common operations we can perform on it</p>



<p class="wp-block-paragraph">We begin by declaring a class called DoublyLinkedList and initializing the head pointer to None</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class DoublyLinkedList(object):
   def __init__(self):
       self.head = None</pre>



<h2 class="wp-block-heading">Inserting an element in a Doubly Linked List</h2>



<p class="wp-block-paragraph">We will now look at how we can insert a new node in a doubly linked list</p>



<p class="wp-block-paragraph">There are 3 scenarios that can occur while inserting a node in a list.</p>



<ol class="wp-block-list"><li>Inserting at the front of the list</li><li>Inserting at the back of the list</li><li>Inserting at a random position in the list</li></ol>



<h2 class="wp-block-heading">Inserting a node at the front of the list</h2>



<p class="wp-block-paragraph">We start by defining a function called <em>insert_front</em> which takes in a node as an input parameter. We then check if the list is empty or not. If the list is empty we assign the head pointer to the newly created node. If the list is not empty i.e. the head pointer is not None we assign the next pointer of the newly created node to the head of the list and the prev pointer of the head to the node. We then reassign the head pointer to point to the newly created node.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def insert_front(self, node):
       if self.head is not None:
           node.next = self.head
           self.head.prev = node
           self.head = node
       else:
           self.head = node
</pre>



<p class="wp-block-paragraph"><strong>Inserting a node at the back of the list</strong></p>



<p class="wp-block-paragraph">We will now look at how to insert a node at the end of the list or the tail of the list.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def insert_back(self, node):
        if self.head is not None:
            current_node = self.head
            while(current_node.next is not None):
                current_node = current_node.next
            current_node.next = node
            node.prev = current_node
        else:
            self.head = node</pre>



<p class="wp-block-paragraph">We define a function called <em>insert_back</em> which takes in a node as an input parameter. We again check if the list is empty or not. If the list is not empty we point the head to the new node. If the list is not empty i.e. there are already some nodes present in the list, we&nbsp; traverse the list till we reach the tail of the list. Once we are at the tail of the list we assign the next pointer of the last node to point to the new node and the previous pointer of the node to point to the previous tail of the list. At the end of this operation the new node becomes the tail of the list.</p>



<h2 class="wp-block-heading">Inserting at a random position in the list</h2>



<p class="wp-block-paragraph">We will now look at how to insert a new node in a list at a random position. We first check if the list is empty or not. If the list is empty we insert the node at the front of the list by calling the <em>insert_front </em>function we had implemented. If the list is not empty then we initialize a counter variable and initialize the current node to point to the head of the list. We then go through the list and keep updating the counter and the current node. As soon as we reach the index position where we would like to insert the node, we point the node to the next pointer of the current node, the previous pointer of the node to the current node, and the next pointer of the current node to the newly created node.&nbsp;</p>



<p class="wp-block-paragraph">We also check if the next of the new node is the last element or node. If it is not the last element in the list, we point the previous pointer of the next node to the new node.  </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def insert(self, node, index):
       if self.head is not None:
           current_counter = 1
           current_node = self.head
           while current_node is not None:
               if current_counter == (index-1):
                   node.next = current_node.next
                   node.prev = current_node
                   current_node.next = node
                   if node.next is not None:
                       node.next.prev = node
               current_node = current_node.next
               current_counter += 1
       else:
           print('List is empty')
           self.insert_front(node)</pre>



<h2 class="wp-block-heading">Deleting an element in a DLL</h2>



<p class="wp-block-paragraph">We will now look at another important operation we can perform on a doubly linked list. We begin by defining a function called <em> delete. </em>The function will take the node value we would like to delete from the list. We then check if the list is empty or not. If the list is empty then we return from the function. If the list is not empty, we will check if the node we would like to delete is the head node or not. If it is the head node we delete the node and assign the head pointer to None. If the node we would like to delete is not the head node, we will first traverse through the list to find the node, once we find the node in the list we will first declare the node  as a temporary node. The next pointer of the previous element in the list will point to the next pointer of the temporary node and the previous pointer of the next node in the list will point to the previous node. We then assign the temporary node to None and delete the node. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def delete(self, value):
       if self.head is None:
           print('Doubly Linked List is empty')
           return
       if self.head.next == None:
           if self.head.data ==  value:
               temp_node = self.head
               self.head = None
               del temp_node
               return
           else:
               print("Element is not found in our list")
               return
       else:
           temp_node = self.head.next
           while temp_node is not None:
               if temp_node.data == value:
                   temp_node.prev.next = temp_node.next
                   temp_node.next.prev = temp_node.prev
                   temp_node = None
                   return
               temp_node = temp_node.next
           if temp_node.data == value:
               temp_node.prev.next = None
               del temp_node
               return
           print("Element is not found in the list")</pre>



<h2 class="wp-block-heading">Summary</h2>



<p class="wp-block-paragraph">In this blog post you learned how to implement a doubly linked list in python. We also looked at how to perform some common operations on a list like insertion and deletion.</p>



<p class="wp-block-paragraph"><strong>You can find the entire code below</strong></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Node(object):
   def __init__(self, value):
       self.data = value
       self.prev = None
       self.next = None
 
class DoublyLinkedList(object):
   def __init__(self):
       self.head = None
 
   def insert_front(self, node):
       if self.head is not None:
           node.next = self.head
           self.head.prev = node
           self.head = node
       else:
           self.head = node
 
   def insert_back(self, node):
       if self.head is not None:
           current_node = self.head
           while(current_node.next is not None):
               current_node = current_node.next
           current_node.next = node
           node.prev = current_node
       else:
           self.head = node
 
 
   def insert(self, node, index):
       if self.head is not None:
           current_counter = 1
           current_node = self.head
           while current_node is not None:
               if current_counter == (index-1):
                   node.next = current_node.next
                   node.prev = current_node
                   current_node.next = node
                   if node.next is not None:
                       node.next.prev = node
               current_node = current_node.next
               current_counter += 1
       else:
           print('List is empty')
           self.insert_front(node)
 
 
   def delete(self, value):
       if self.head is None:
           print('Doubly Linked List is empty')
           return
       if self.head.next == None:
           if self.head.data ==  value:
               temp_node = self.head
               self.head = None
               del temp_node
               return
           else:
               print("Element is not found in our list")
               return
       else:
           temp_node = self.head.next
           while temp_node is not None:
               if temp_node.data == value:
                   temp_node.prev.next = temp_node.next
                   temp_node.next.prev = temp_node.prev
                   temp_node = None
                   return
               temp_node = temp_node.next
           if temp_node.data == value:
               temp_node.prev.next = None
               del temp_node
               return
           print("Element is not found in the list")
 
   def display(self,):
       current_node = self.head
       while current_node is not None:
           if current_node.next is None:
               print(current_node.data,  end=' ', flush=True)
           else:
               print(current_node.data,  end='-->', flush=True)
           previous_node = current_node
           current_node = current_node.next
 
       print('\n')
       print('List in reverse order')
      
       while previous_node is not None:
           if previous_node.prev is None:
               print(previous_node.data,  end=' ', flush=True)
           else:
               print(previous_node.data,  end='-->', flush=True)
           previous_node = previous_node.prev
       print('\n')
 
if __name__ == "__main__":
   node1 = Node(12)
   node2 = Node(13)
 
   dll = DoublyLinkedList()
   dll.insert_front(node1)
   dll.insert_front(node2)
   dll.display()
 
   dll.insert_back(Node(14))
   dll.insert_back(Node(26))
 
   dll.insert_front(Node(1))
 
 
   dll.display()
 
 
 
   dll.insert(Node(2), 2)
   dll.insert(Node(5), 3)
 
   dll.display()
 
 
   print('Deleting node')
   dll.delete(5)
   dll.display()
</pre>
<p>The post <a href="https://blog.finxter.com/doubly-linked-list-in-python/">Doubly Linked List in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Linked Lists in Python</title>
		<link>https://blog.finxter.com/linked-lists-in-python/</link>
		
		<dc:creator><![CDATA[Neeraj Sujan]]></dc:creator>
		<pubDate>Fri, 05 Feb 2021 15:05:14 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Python List]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=22952</guid>

					<description><![CDATA[<p>In this blog post you will learn how to implement a linked list in Python from scratch. We will understand the internals of linked lists, the computational complexity of using a linked list and some advantages and disadvantages of using a linked list over an array. Introduction Linked list is one of the most fundamental ... <a title="Linked Lists in Python" class="read-more" href="https://blog.finxter.com/linked-lists-in-python/" aria-label="Read more about Linked Lists in Python">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/linked-lists-in-python/">Linked Lists in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">In this blog post you will learn how to implement a linked list in Python from scratch. We will understand the internals of linked lists, the computational complexity of using a linked list and some advantages and disadvantages of using a linked list over an array.</p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Linked Lists in Python" width="937" height="527" src="https://www.youtube.com/embed/Eh9I-QxWCUY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Introduction</h2>



<p class="wp-block-paragraph">Linked <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list </a>is one of the most <strong>fundamental data structure in programming</strong>. Imagine you are building a directory of image files and each of these files are linked to each other. How could we model this problem? There are various data structures at our disposal to solve this problem. You could use an array to store the files in a contiguous block of memory. The advantage of using an array is its quick access time. While an array does help us in accessing the files in O(1) time, there are some disadvantages of using an array if we would like to insert a new file or delete a new file. A linked list helps us in <a href="https://blog.finxter.com/python-list-insert-method/" target="_blank" rel="noreferrer noopener" title="Python List insert() Method">inserting </a>and <a href="https://blog.finxter.com/how-to-remove-items-from-a-list-while-iterating/" target="_blank" rel="noreferrer noopener" title="How To Remove Items From A List While Iterating?">deleting </a>an element in constant time.</p>



<p class="wp-block-paragraph">A linked list is represented by a collection of nodes and each node is linked to the other node by using a pointer.&nbsp; Figure 1 demonstrates the concept of a linked list.</p>



<figure class="wp-block-image"><img decoding="async" src="https://docs.google.com/drawings/u/1/d/stWf3SPLtk8uIx7kfSJVx0Q/image?w=624&amp;h=62&amp;rev=153&amp;ac=1&amp;parent=1QhlftODZ4jjUW8I4WMrpMRPIDsuYpraqfYWv5xPJ0XQ" alt=""/></figure>



<p class="wp-block-paragraph">&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; Figure 1: Linked List</p>



<p class="wp-block-paragraph">As you can see in Figure 1, a linked list is created by connecting the next pointer of a node with another node. Let us now get started by opening our editor and constructing a singly linked list in Python.</p>



<p class="wp-block-paragraph">A linked list  has a collection of nodes, so we first start by constructing a <code>Node</code> class</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Node(object):
   def __init__(self, value):
       self.data = value
       self.next = None</pre>



<p class="wp-block-paragraph">The <code>Node</code> class has two member variables — the data and the pointer called next which points to the next node. Whenever a new node is created, the next pointer will be set to a <code>None</code> value.</p>



<p class="wp-block-paragraph">Now let us begin by constructing the Linked List class. The <a href="https://blog.finxter.com/python-one-line-class/" target="_blank" rel="noreferrer noopener" title="Python One Line Class">class </a>will be composed of the following functionalities</p>



<ol class="wp-block-list"><li><strong>Inserting </strong>an element at the front of the Linked List</li><li><strong>Inserting </strong>an element at the back or the tail of the Linked List</li><li><strong>Deleting </strong>an element at a specified index in the Linked List</li><li><strong>Searching </strong>the Linked List for a specified data value</li><li><strong>Displaying </strong>the Linked List</li></ol>



<p class="wp-block-paragraph">Let us begin by constructing the Linked List and initializing the member variables</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class LinkedList(object):
   def __init__(self):
       self.head = None</pre>



<h2 class="wp-block-heading">Operations on a Linked list</h2>



<p class="wp-block-paragraph">Next, you&#8217;ll learn about all the discussed linked list operations&#8212;and how to implement them in Python!</p>



<h3 class="wp-block-heading">Inserting an element at the front of the Linked List</h3>



<p class="wp-block-paragraph">In order to insert a new node at the front of the list we first need to <a href="https://blog.finxter.com/how-to-check-if-a-list-is-empty-in-python/" target="_blank" rel="noreferrer noopener" title="How To Check If a List Is Empty In Python?">check if the list is empty</a> or not. We do this by checking the head of the list. If the list is empty then we can point the head to the newly created node. If, however, the list is not empty, we will point the next value of the newly created node to the head of the linked list, and we will reassign the head pointer to point to the newly created node. The code snippet below  demonstrates how you can implement this functionality.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class LinkedList(object):
   def __init__(self):
       self.head = None
 
   def insert_front(self, node):
       if self.head is not None:
           node.next = self.head
           self.head = node
       else:
           self.head = node</pre>



<h3 class="wp-block-heading">Inserting an element at the end of the list</h3>



<p class="wp-block-paragraph">In order to insert an element at the end of the list we need to traverse the list till we reach the tail of the list and as soon as we reach the tail of the list we point the next pointer of the tail to the newly created node.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def insert_back(self, node):
       if self.head is not None:
           current_node = self.head
           while current_node.next is not None:
               current_node = current_node.next
           current_node.next = node
       else:
           self.head = node</pre>



<h3 class="wp-block-heading">Deleting an element at a specified index in the Linked List</h3>



<p class="wp-block-paragraph">Now we will look at how to delete an element from the linked list given an index value.</p>



<p class="wp-block-paragraph">There are <strong>three conditions</strong> we need to check if we would like to <strong>delete a node from a linked list</strong>.</p>



<ol class="wp-block-list"><li><strong>Deleting a node if the linked list is empty:</strong> We will first check if the linked list is empty or not. If the list is empty we print a message that the linked list is empty and return from the function.</li><li><strong>Deleting the head of the linked list: </strong>The second condition arises when we would like to delete the first node or in other words the head of the linked list. To remove the head of the linked list we first create a temporary node to point to the head of the node and then reassign the head pointer to the next node of the original head. We then delete the temporary node.</li><li><strong>Deleting a node at an arbitrary position:</strong> In order to delete a node at an arbitrary position we traverse through the linked list and check if the value that we would like to delete matches with that of the current node. If a match is found we reassign the previous node’s next pointer to the current node’s next node. We then delete the current node.</li></ol>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def delete(self, value):
       if self.head is None:
           print('Linked List is empty')
           return
       if self.head.data == value:
           node_to_delete = self.head
           self.head = self.head.next
           del node_to_delete
           return
       # deletion at arbitary position
       current_node = self.head
       while current_node is not None:
           if current_node.next.data == value:
               temp_node = current_node.next
               current_node.next = temp_node.next
               del temp_node
               return
           current_node = current_node.next
</pre>



<h3 class="wp-block-heading">Searching the Linked List for a specified value</h3>



<p class="wp-block-paragraph">We will now look at searching for a given value in a linked list. In order to achieve this we start at the head of the linked list and at every iteration we check for the node’s value. If a match is found we print the location of that node by keep track of a <code>counter</code> variable that we have defined. If no match is found we jump to the next node and repeat the steps to check for a match.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def search(self, value):
       counter = 1
       current_node = self.head
       while current_node is not None:
           if current_node.data == value:
               print('Node with value {} found at location {}'.format(value, counter))
               return
           current_node = current_node.next
           counter += 1
       print('Node with value {} not found'.format(value))
</pre>



<h3 class="wp-block-heading">Displaying the Linked List</h3>



<p class="wp-block-paragraph">We will create a function called display to traverse through the linked list and print the data value of the node. Once we print the value we jump to the next node by updating the value of the current node.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def display(self,):
       current_node = self.head
       while current_node is not None:
           if current_node.next is None:
               print(current_node.data,  end=' ', flush=True)
           else:
               print(current_node.data,  end='-->', flush=True)
           current_node = current_node.next
       print('\n')
</pre>



<h2 class="wp-block-heading">Demonstration</h2>



<p class="wp-block-paragraph">Let us now see all the functionalities in action. We start by creating four nodes with the following values</p>



<figure class="wp-block-image"><img decoding="async" src="https://docs.google.com/drawings/u/1/d/sKXbq-fqgeIZbmY_1qqWl2A/image?w=624&amp;h=62&amp;rev=55&amp;ac=1&amp;parent=1QhlftODZ4jjUW8I4WMrpMRPIDsuYpraqfYWv5xPJ0XQ" alt=""/></figure>



<p class="wp-block-paragraph">We then create an instance of the <code>LinkedList</code> class and insert the above nodes at the back of the linked list.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">node1 = Node(12)
node2 = Node(13)
node3 = Node(14)
node4 = Node(15)
 
ll = LinkedList()
ll.insert_back(node1)
ll.insert_back(node2)
ll.insert_back(node3)
ll.insert_back(node4)
ll.display()
</pre>



<p class="wp-block-paragraph">We can see the output as follows</p>



<pre class="wp-block-preformatted">12--&gt;13--&gt;14--&gt;15</pre>



<p class="wp-block-paragraph">Next we will insert a node at the front of the linked list as follows.</p>



<figure class="wp-block-image"><img decoding="async" src="https://docs.google.com/drawings/u/1/d/sm4rndCVzCgvqR7ttXXtqdg/image?w=624&amp;h=97&amp;rev=50&amp;ac=1&amp;parent=1QhlftODZ4jjUW8I4WMrpMRPIDsuYpraqfYWv5xPJ0XQ" alt=""/></figure>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">node5 = Node(1)
ll.insert_front(node5)
ll.display()
</pre>



<p class="wp-block-paragraph">On calling the display function, we get the following output</p>



<pre class="wp-block-preformatted">1--&gt;12--&gt;13--&gt;14--&gt;15<strong>&nbsp;</strong></pre>



<p class="wp-block-paragraph">Now we will look at the search functionality to <a href="https://blog.finxter.com/daily-python-puzzle-bsearch/" target="_blank" rel="noreferrer noopener" title="The Binary Search Algorithm in Python">search </a>for a node with a specific data value and get the position of that node in the linked list.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ll.search(12)
ll.search(1)
ll.search(5)
ll.search(15)</pre>



<p class="wp-block-paragraph">As we can see in the output below we can observe that the node with the value 12 is at position 2, the node with the value 1 is at the first position, the node with the value 5 is not there in the list and the node with the value 15 is located at the position 5.</p>



<ul class="wp-block-list"><li><em>Node with value 12 found at location 2</em></li><li><em>Node with value 1 found at location 1</em></li><li><em>Node with value 5 not found</em></li><li><em>Node with value 15 found at location 5</em></li></ul>



<p class="wp-block-paragraph">We will now delete a node with a given value</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""> 
ll.delete(12)
ll.display()
</pre>



<p class="wp-block-paragraph">As we can see in the output below we were able to delete the node with the value 12 and update its previous pointer i.e. the node with the value 1 now points to the node with the value 13.</p>



<pre class="wp-block-preformatted">1--&gt;13--&gt;14--&gt;15&nbsp;</pre>



<p class="wp-block-paragraph">As a last step we will see what happens if we <a href="https://blog.finxter.com/python-list-insert-method/" target="_blank" rel="noreferrer noopener" title="Python List insert() Method">insert </a>a new node at the specific location. In the example below we will try to insert a node with value 12 at the position 2, delete the node with the value 15 and 1 and observe the output after each step.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ll.insert(Node(12), 2)
ll.display()
 
ll.delete(15)
ll.display()
 
ll.delete(1)
ll.display()
</pre>



<p class="wp-block-paragraph">We get the following output</p>



<pre class="wp-block-preformatted">1-->12-->13-->14-->15 
1-->12-->13-->14 
12-->13-->14 </pre>



<p class="wp-block-paragraph">You can see the entire code below</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Node(object):
   def __init__(self, value):
       self.data = value
       self.next = None
 
class LinkedList(object):
   def __init__(self):
       self.head = None
 
   def insert_front(self, node):
       if self.head is not None:
           node.next = self.head
           self.head = node
       else:
           self.head = node
 
   def insert_back(self, node):
       if self.head is not None:
           current_node = self.head
           while current_node.next is not None:
               current_node = current_node.next
           current_node.next = node
       else:
           self.head = node
 
   def insert(self, node, index):
       if self.head is not None:
           current_counter = 1
           current_node = self.head
           while current_node is not None:
               if current_counter == (index - 1):
                   node.next = current_node.next
                   current_node.next = node
               current_node = current_node.next
               current_counter +=1
       else:
           print('List is empty')
           self.insert_front(node)
 
   def search(self, value):
       counter = 1
       current_node = self.head
       while current_node is not None:
           if current_node.data == value:
               print('Node with value {} found at location {}'.format(value, counter))
               return
           current_node = current_node.next
           counter += 1
       print('Node with value {} not found'.format(value))
 
 
 
   def delete(self, value):
       if self.head is None:
           print('Linked List is empty')
           return
       if self.head.data == value:
           node_to_delete = self.head
           self.head = self.head.next
           del node_to_delete
           return
       # deletion at arbitary position
       current_node = self.head
       while current_node is not None:
           if current_node.next.data == value:
               temp_node = current_node.next
               current_node.next = temp_node.next
               del temp_node
               return
           current_node = current_node.next
      
 
   def display(self,):
       current_node = self.head
       while current_node is not None:
           if current_node.next is None:
               print(current_node.data,  end=' ', flush=True)
           else:
               print(current_node.data,  end='-->', flush=True)
           current_node = current_node.next
       print('\n')
 
  
 
 
 
if __name__ == "__main__":
   node1 = Node(12)
   node2 = Node(13)
   node3 = Node(14)
   node4 = Node(15)
 
   ll = LinkedList()
   ll.insert_back(node1)
   ll.insert_back(node2)
   ll.insert_back(node3)
   ll.insert_back(node4)
 
   ll.display()
 
   node5 = Node(1)
   ll.insert_front(node5)
   ll.display()
   ll.search(12)
   ll.search(1)
   ll.search(5)
   ll.search(15)
 
   ll.delete(12)
   ll.display()
 
   ll.insert(Node(12), 2)
   ll.display()
 
   ll.delete(15)
   ll.display()
 
   ll.delete(1)
   ll.display()
</pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">In this tutorial we saw how to implement a linked list from scratch. We then saw how to do some common operations like insertion, deletion, search and traversal on a linked list. Linked Lists have an advantage when we would like to insert or delete a node from our list. We can achieve both these tasks in constant time. In the next tutorial we will look at some common linked list problems and how to solve them efficiently.&nbsp;</p>
<p>The post <a href="https://blog.finxter.com/linked-lists-in-python/">Linked Lists in Python</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Deploying a machine learning model in FastAPI</title>
		<link>https://blog.finxter.com/deploying-a-machine-learning-model-in-fastapi/</link>
		
		<dc:creator><![CDATA[Neeraj Sujan]]></dc:creator>
		<pubDate>Tue, 26 Jan 2021 10:45:35 +0000</pubDate>
				<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=22109</guid>

					<description><![CDATA[<p>If you aspire to work in the field of machine learning, you might have to deploy your machine learning model in production. In this blog post you will learn how to deploy a simple linear regression model in FastAPI. FastAPI is a modern web framework to deploy your application in Python. Getting Started Let us ... <a title="Deploying a machine learning model in FastAPI" class="read-more" href="https://blog.finxter.com/deploying-a-machine-learning-model-in-fastapi/" aria-label="Read more about Deploying a machine learning model in FastAPI">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/deploying-a-machine-learning-model-in-fastapi/">Deploying a machine learning model in FastAPI</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">If you aspire to work in the field of machine learning, you might have to deploy your machine learning model in production. In this blog post you will learn how to deploy a<a href="https://blog.finxter.com/simple-linear-regression/" target="_blank" rel="noreferrer noopener" title="Simple Linear Regression"> simple linear regression</a> model in FastAPI. <a href="https://fastapi.tiangolo.com/" target="_blank" rel="noreferrer noopener">FastAPI</a> is a modern web framework to deploy your application in Python.</p>



<h2 class="wp-block-heading">Getting Started</h2>



<p class="wp-block-paragraph">Let us get started by installing the libraries needed to build our application.</p>



<p class="wp-block-paragraph">We will create a virtual environment for development purpose. Using a virtual environment gives us the flexibility to separate dependencies for different Python projects.</p>



<p class="wp-block-paragraph">Go to a directory where you would like to create this project and in a separate terminal execute the following command</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">python3 -m venv fastapi-env</pre>



<p class="wp-block-paragraph">Once you have the environment setup, we can activate the environment by executing the following command</p>



<pre class="EnlighterJSRAW" data-enlighter-language="powershell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">source fastapi-env/bin/activate</pre>



<p class="wp-block-paragraph">Now your environment is activated, and we can begin by installing the necessary dependencies for our project.</p>



<p class="wp-block-paragraph">Let us begin by creating a <code>requirements.txt</code> file which will include all the libraries that we would be using in our project.</p>



<p class="wp-block-paragraph">We would be needing the FastAPI library and the <code><a href="https://blog.finxter.com/scikit-learn-cheat-sheets/" target="_blank" rel="noreferrer noopener" title="[Collection] 10 Scikit-Learn Cheat Sheets Every Machine Learning Engineer Must Have">sklearn</a></code> library for running our regression model.</p>



<p class="wp-block-paragraph">Open a new file, name it <code>requirements.txt</code> and insert the following lines:</p>



<pre class="wp-block-preformatted"><code><strong># requirements.txt</strong>
fastapi
uvicorn
sklearn</code></pre>



<p class="wp-block-paragraph">You can now install the libraries by executing the following command</p>



<pre class="EnlighterJSRAW" data-enlighter-language="powershell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip3 install -r requirements.txt</pre>



<h2 class="wp-block-heading">Building a Linear Regression Model</h2>



<p class="wp-block-paragraph">We will be using a trained linear regression model to predict the quantitative measure of disease prediction. You can use the following<a href="https://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html#sphx-glr-auto-examples-linear-model-plot-ols-py" target="_blank" rel="noreferrer noopener"> link </a>to train a linear regression model. Once you have the model trained you can save the model using the <code>joblib</code> library</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from joblib import dump, load
dump(regr , 'model.joblib')</pre>



<p class="wp-block-paragraph">We save the model in the current directory and give it a name&#8211;in our case we have given the model a name, <code>model.joblib</code>.</p>



<h2 class="wp-block-heading">Serving Your Model</h2>



<p class="wp-block-paragraph">Now we begin by understanding how FastAPI works and how we can implement a simple API to serve a machine learning request.</p>



<p class="wp-block-paragraph">We begin by importing the libraries</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from fastapi import FastAPI
from joblib import load
import numpy as np
</pre>



<p class="wp-block-paragraph">We then load our model and declare an instance of the FastAPI <a href="https://blog.finxter.com/top-python-oop-cheat-sheets/" target="_blank" rel="noreferrer noopener" title="Top 10 Python OOP Cheat Sheets">class</a>. We store this in a variable called <code>app</code>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">app = FastAPI()
model = load('model.joblib')
</pre>



<p class="wp-block-paragraph">We then implement a function for our index route. Whenever a user or a client tries to access the index route, the function <code>root()</code> is called and a <code>“Hello World”</code> message is sent back.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@app.get("/")
async def root():
   return {"message": "Hello World"}</pre>



<p class="wp-block-paragraph">You can run your app by using the <code>uvicorn</code> library which is an asynchronous server which spins up your app.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">if __name__ == '__main__':
   uvicorn.run(app, host='127.0.0.1', port=8000)
</pre>



<p class="wp-block-paragraph">Once your app is running we can go to <code>localhost:8000</code> and see the message <code>“Hello World”</code> displayed</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="624" height="444" src="https://blog.finxter.com/wp-content/uploads/2021/01/image-167.png" alt="" class="wp-image-22115" srcset="https://blog.finxter.com/wp-content/uploads/2021/01/image-167.png 624w, https://blog.finxter.com/wp-content/uploads/2021/01/image-167-300x213.png 300w, https://blog.finxter.com/wp-content/uploads/2021/01/image-167-150x107.png 150w" sizes="auto, (max-width: 624px) 100vw, 624px" /></figure></div>



<p class="wp-block-paragraph">We will now implement the predict function and since we need to send a <code>json</code> file with our data we will define it as post request using the <code>@app.post</code> <a href="https://blog.finxter.com/a-3-min-primer-on-python-decorators/" target="_blank" rel="noreferrer noopener" title="A 3-Min Primer on Python Decorators">decorator </a>function.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@app.post("/predict")
def predict(data_diabetes:float):
   data = np.array([[data_diabetes]])
   prediction = model.predict(data)
   return {
       'prediction': prediction[0],
   }
</pre>



<p class="wp-block-paragraph">As you can see in the above code snippet, first the data is transformed into a <a href="https://blog.finxter.com/numpy-tutorial/" title="NumPy Tutorial – Everything You Need to Know to Get Started" target="_blank" rel="noreferrer noopener">NumPy array</a> since our model expects an array of <a href="https://blog.finxter.com/how-to-get-shape-of-array/" target="_blank" rel="noreferrer noopener" title="How to Get the Shape of a Numpy Array?">shape </a>1&#215;1. We can these use this transformed vector value to call the predict function of the model, which will return the prediction or the quantitative metric of progression of diabetes.</p>



<p class="wp-block-paragraph">Let us see the entire code in action</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from fastapi import FastAPI
from joblib import load
import numpy as np
app = FastAPI()

model = load('model.joblib')



@app.get("/")
async def root():
   return {"message": "Hello World"}


@app.post("/predict")
def predict(data_diabetes:float):
   data = np.array([[data_diabetes]])
   prediction = model.predict(data)
   return {
       'prediction': prediction[0],
   }


if __name__ == '__main__':
   uvicorn.run(app, host='127.0.0.1', port=8000)

</pre>



<h2 class="wp-block-heading">Calling Your Endpoint</h2>



<p class="wp-block-paragraph">You can call this endpoint using a client library in Python or using a simple curl command to test the functionality of our application.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="powershell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">curl -X POST "http://localhost:8000/predict?data_diabetes=0.07786339" -H  "accept: application/json" -d ""</pre>



<p class="wp-block-paragraph">You get the following response back</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">{"prediction":225.97324232953468}</pre>



<p class="wp-block-paragraph">The model outputted a value of 225.97324 and this was sent back as a response to our client.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p class="wp-block-paragraph">In this blog post you learned how to deploy a simple machine learning model in FastAPI. FastAPI is a powerful web framework to deploy and build scalable Python applications.</p>



<p>The post <a href="https://blog.finxter.com/deploying-a-machine-learning-model-in-fastapi/">Deploying a machine learning model in FastAPI</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Proportional Sampling Using Weighted Values</title>
		<link>https://blog.finxter.com/proportional-sampling-using-weighted-values/</link>
		
		<dc:creator><![CDATA[Neeraj Sujan]]></dc:creator>
		<pubDate>Sat, 16 Jan 2021 13:30:28 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Data Science]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<guid isPermaLink="false">https://blog.finxter.com/?p=21272</guid>

					<description><![CDATA[<p>Probability and Statistics play a very important role in the field of data science and machine learning. In this blog post you will learn the concept of proportional sampling and how can we implement it from scratch without using any library Proportional Sampling Let us take an example of tossing a die to better understand ... <a title="Proportional Sampling Using Weighted Values" class="read-more" href="https://blog.finxter.com/proportional-sampling-using-weighted-values/" aria-label="Read more about Proportional Sampling Using Weighted Values">Read more</a></p>
<p>The post <a href="https://blog.finxter.com/proportional-sampling-using-weighted-values/">Proportional Sampling Using Weighted Values</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Probability and Statistics play a very important role in the field of <a href="https://blog.finxter.com/artificial-intelligence-machine-learning-deep-learning-and-data-science-whats-the-difference/" title="Artificial Intelligence, Machine Learning, Deep Learning, and Data Science — What’s the Difference?" target="_blank" rel="noreferrer noopener">data science and machine learning</a>. In this blog post you will learn the concept of <strong>proportional sampling</strong> and how can we implement it from scratch <strong>without using any library</strong></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Proportional Sampling Using Weighted Values" width="937" height="527" src="https://www.youtube.com/embed/qsLmj-6AktU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<h2 class="wp-block-heading">Proportional Sampling</h2>



<p class="wp-block-paragraph">Let us take an example of tossing a die to better understand the concept of proportional sampling. An unbiased die is a die in which the probability of getting a number between 1 and 6 is equal. Let us now imagine that the die is biased i.e a weight value is given to each side of the die.</p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td></tr></tbody></table><figcaption><strong>Fig 1</strong>: Die represented in the form of an array</figcaption></figure>



<p class="wp-block-paragraph">                                                       </p>



<figure class="wp-block-table is-style-stripes"><table><tbody><tr><td>20</td><td>12</td><td>60</td><td>58</td><td>33</td><td>10</td></tr></tbody></table><figcaption><strong>Fig 2</strong>: Weight values given to the different sides of a die</figcaption></figure>



<p class="wp-block-paragraph">                      </p>



<p class="wp-block-paragraph">Proportional sampling is a technique in which the probability of selecting a number is proportional to the weight of that number. So, for instance if we run&nbsp; an experiment&nbsp; of tossing a die 100 times, then the probability of getting a 6 would be the lowest since the weight value of the side 6 is 10 which is the lowest amongst all other weight values. On the other hand, the probability of getting a 4 would be the highest since the weight value for 3 is 60 which is the highest amongst all other values.</p>



<p class="wp-block-paragraph">There are 3 essentials steps to proportionally sample a number from a list.</p>



<ol class="wp-block-list"><li>Computing the <a href="https://blog.finxter.com/numpy-cumsum/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to NumPy Cumsum in Python">cumulative normalized sum</a> values</li><li>Choosing a random value from uniform distribution</li><li>Sampling a value</li></ol>



<h2 class="wp-block-heading">Cumulative Normalized Sum</h2>



<p class="wp-block-paragraph">In order to compute the cumulative normalized sum value we first need to calculate the total sum of the weight values and then normalize the weight values by dividing each weight value by the total sum. After normalizing the weight values, we will have all the values between 0 and 1 and the sum of all the values will always be equal to 1.</p>



<p class="wp-block-paragraph">Let us declare a variable called dice and weights which represents the 6 sides of the die and the corresponding weight values</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dice = [1, 2, 3, 4, 5, 6]
weights = [20, 12, 60, 58, 33, 10]</pre>



<p class="wp-block-paragraph">We will now compute the sum of all weights and store it in a variable called <code>total_sum</code>. We  can use the<a href="https://blog.finxter.com/python-built-in-functions/" title="Python Built-In Functions" target="_blank" rel="noreferrer noopener"> in-built</a> sum function to do this.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">total_sum = sum(weights)
normalized_weights = [weight/total_sum for weight in weights]
print(normalized_weights)</pre>



<p class="wp-block-paragraph">The normalized weights have values between 0 and 1 and the sum of all the values is equal to 1</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[0.10362694300518134, 0.06217616580310881, 0.31088082901554404, 0.3005181347150259, 0.17098445595854922, 0.05181347150259067]</pre>



<p class="wp-block-paragraph">The cumulative sum is used for monitoring change detection in a sequential data-set. Let us denote the cumulative sum by a variable called <code>weight_cum_sum</code> and computing it as follows</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">weight_cum_sum[0] = normalized_weights[0]
weight_cum_sum[1] = weight_cum_sum[0] +  normalized_weights[1]
weight_cum_sum[2] = weight_cum_sum[1] +  normalized_weights[2]
weight_cum_sum[3] = weight_cum_sum[2] +  normalized_weights[3]
weight_cum_sum[4] = weight_cum_sum[3] +  normalized_weights[4]
weight_cum_sum[5] = weight_cum_sum[4] +  normalized_weights[5]
</pre>



<p class="wp-block-paragraph">We can do this efficiently in python by running a <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops"><code>for </code>loop</a> and appending the cumulative sum values in a <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list</a></p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cum_sum = [normalized_weights[0]]
for i in range(1, len(normalized_weights)):
    cum_sum.append(cum_sum[i-1] +  normalized_weights[i])</pre>



<p class="wp-block-paragraph">If we <a href="https://blog.finxter.com/python-print/" target="_blank" rel="noreferrer noopener" title="Python print()">print </a><code>cum_sum</code>, we will get the following values</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[0.10362694300518134, 0.16580310880829013, 0.47668393782383417,  0.7772020725388601,  0.9481865284974094, 1.0]</pre>



<h2 class="wp-block-heading">Choosing a random value</h2>



<p class="wp-block-paragraph">Now that we have calculated the cumulative sum of the weight values, we will now randomly choose a number between 0 and 1 from a uniform distribution. We can do this by using the uniform function from the random module in python. We will denote this number by r.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from random import uniform
r = uniform(0,1)</pre>



<h2 class="wp-block-heading">Sampling</h2>



<p class="wp-block-paragraph">We will now <a href="https://blog.finxter.com/python-enumerate/" target="_blank" rel="noreferrer noopener" title="Python enumerate() — A Simple Illustrated Guide with Video">loop </a>through the <code>cum_sum</code> array and if the value of r is less than or equal to the <code>cum_sum</code> value at a particular index, then we will return the die value at that index</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for index, value in enumerate(cum_sum):
    if r &lt;= value:
      return dice[index]  </pre>



<p class="wp-block-paragraph">You can see the entire code below</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from random import uniform

def proportional_sampling(dice, weights):
    total_sum = sum(weights)
    normalized_weights = [weight/total_sum for weight in weights]
    cum_sum = [normalized_weights[0]]
    r = uniform(0,1)
    for i in range(1, len(normalized_weights)):
        cum_sum.append(cum_sum[i-1] + normalized_weights[i])
    for index, value in enumerate(cum_sum):
        if r &lt;=  value:
            return dice[index]
       
dice = [1,2,3,4,5,6]
weights = [20, 12, 60, 58, 33, 10]  
sampled_value = proportional_sampling(dice, weights)</pre>



<h2 class="wp-block-heading">Experimentation</h2>



<p class="wp-block-paragraph">We will now run an experiment where will call the <code>proportional_sampling</code> 100 times and analyze the result of sampling a number</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dice_result = {}
for i in range(0, 100):
    sampled_value = proportional_sampling(dice, weights)
    if sampled_value not in dice_result:
        dice_result[sampled_value] = 1
    else:
        dice_result[sampled_value] += 1</pre>



<figure class="wp-block-image"><img decoding="async" src="https://lh5.googleusercontent.com/UWReggNdbKBbTMQU4Wj_n8Zs12VzmWv0Xt8QlZj8MjyDo0vAf5-Ac7xapjnaautCWKsOfW1zMYMQ7eGoogaDH-NZlQBSCRQf5gLzu4PgrW6miwgFuUdmlk7ZuEqhbdSOl9UKEEwy" alt=""/></figure>



<p class="wp-block-paragraph">As you can see from the above figure the probability of getting a 3 is the highest since 3  was given a weight of 60 which was the largest number in the weights array. If we  run this experiment for 1000 iterations instead of 100 you can expect to get even more precise results.</p>



<p>The post <a href="https://blog.finxter.com/proportional-sampling-using-weighted-values/">Proportional Sampling Using Weighted Values</a> appeared first on <a href="https://blog.finxter.com">Be on the Right Side of Change</a>.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: blog.finxter.com @ 2026-10-06 20:45:23 by W3 Total Cache
-->