<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ajinkya Sonawane on Medium]]></title>
        <description><![CDATA[Stories by Ajinkya Sonawane on Medium]]></description>
        <link>https://medium.com/@ajinkyasonawane?source=rss-633ba00874a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Wi9ixaqISpjX7TZb7sgDgA.jpeg</url>
            <title>Stories by Ajinkya Sonawane on Medium</title>
            <link>https://medium.com/@ajinkyasonawane?source=rss-633ba00874a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 23 May 2026 06:34:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajinkyasonawane/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Solving Sudoku Puzzle using Backtracking in Python | Daily Python #29]]></title>
            <link>https://medium.com/daily-python/solving-sudoku-puzzle-using-backtracking-in-python-daily-python-29-99a825042e?source=rss-633ba00874a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/99a825042e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[daily-python]]></category>
            <category><![CDATA[sudoku]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ajinkya Sonawane]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 17:02:50 GMT</pubDate>
            <atom:updated>2020-07-17T18:06:48.959Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a tutorial on solving a sudoku puzzle using Backtracking algorithm in Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5cQ9FrD3F8IYEicdNaW7vA.png" /></figure><blockquote>This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.</blockquote><blockquote>There are no additional requirements for this article.</blockquote><h3>What exactly is a Sudoku Puzzle?</h3><p>According to Wikipedia, <strong>Sudoku</strong> (originally called <strong>Number Place</strong>) is a <a href="https://en.wikipedia.org/wiki/Logic">logic</a>-based, combinatorial number-placement puzzle.</p><p>The objective is to fill a 9×9 grid with digits so that <strong>each column</strong>, <strong>each row</strong>, and <strong>each of the nine 3×3 subgrids</strong> that compose the grid (also called “boxes”, “blocks”, or “regions”) contain all of the digits from 1 to 9.</p><p>The puzzle setter provides a partially completed grid, which for a well-posed puzzle has a single solution.</p><p>Note: The number of classic 9×9 Sudoku solution grids is 6,670,903,752,021,072,936,960 (sequence A107739 in the OEIS), or around 6.67×1021.</p><p>So, generating all the grids and choosing the solution is not efficient. To minimize this task, we can use a Backtracking approach.</p><h3>What is Backtracking?</h3><p>It is algorithmic-technique for finding all solutions to the same computational problems, notably constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate as soon as it determines that the candidate cannot possibly be completed to a valid solution.</p><p>In our problem, we need to traverse each block of the grid, check which digit can be placed in this block, repeat till we have a solution. If a digit cannot be placed in the current block, we go to the previous block and try placing another digit in that block, changing the next possible solution.</p><p>This basically means, whenever we arrive at a dead-end, we go back to the previous choice we made and change our choice, such that we will have a different possible solution.</p><h3>Let’s first find a sudoku problem to solve</h3><p><a href="https://www.kaggle.com/bryanpark/sudoku/data#">1 million Sudoku games</a></p><p>You can either download the CSV file or copy a string of the sudoku puzzle problem and create a grid in the code.</p><h3>Forming the Puzzle</h3><pre>#Forming the Puzzle Grid<br>def form_grid(puzzle_string):<br>    global grid<br>    print(&#39;The Sudoku Problem&#39;)<br>    for i in range(0, len(puzzle_string), 9):<br>        row = puzzle_string[i:i+9]<br>        temp = []<br>        for block in row:<br>            temp.append(int(block))<br>        grid.append(temp)    <br>    printGrid()</pre><h3>Function to print the Grid</h3><pre>#Function to print the grid<br>def printGrid():<br>    global grid<br>    for row in grid:<br>        print(row)</pre><h3>Function to check if a digit can be placed in the current block</h3><pre>#Function to check if a digit can be placed in the given block<br>def possible(row,col,digit):<br>    global grid<br>    for i in range(0,9):<br>        if grid[row][i] == digit:<br>            return False<br>    for i in range(0,9):<br>        if grid[i][col] == digit:<br>            return False<br>    square_row = (row//3)*3<br>    square_col = (col//3)*3<br>    for i in range(0,3):<br>        for j in range(0,3):<br>            if grid[square_row+i][square_col+j] == digit:<br>                return False    <br>    return True</pre><h3>Traversing through all blocks w/ Backtracking</h3><pre>def solve():<br>    global grid<br>    for row in range(9):<br>        for col in range(9):<br>            if grid[row][col] == 0:<br>                for digit in range(1,10):<br>                    if possible(row,col,digit):<br>                        grid[row][col] = digit<br>                        solve()<br>                        grid[row][col] = 0  #Backtrack step<br>                return<br>    print(&#39;\nThe Solution&#39;)<br>    printGrid()</pre><h3>Finally, passing the Grid and calling the function to Solve the Puzzle</h3><pre>puzzle_string = &quot;004300209005009001070060043006002087190007400050083000600000105003508690042910300&quot;<br>grid = []<br>form_grid(puzzle_string)<br>solve()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*S0Ud1JP6iX8XnHtz1m-Ryg.png" /><figcaption>Snip of the output of the above code</figcaption></figure><p><em>I hope this article was helpful, do leave some claps if you liked it.</em></p><h4>Follow the Daily Python Challenge here:</h4><ul><li><a href="https://github.com/Ajinkya-Sonawane/Daily-Python">Ajinkya-Sonawane/Daily-Python</a></li><li><a href="https://instagram.com/daily.py">Login * Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99a825042e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-python/solving-sudoku-puzzle-using-backtracking-in-python-daily-python-29-99a825042e">Solving Sudoku Puzzle using Backtracking in Python | Daily Python #29</a> was originally published in <a href="https://medium.com/daily-python">Daily Python</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python script to merge PDF Files | Daily Python #28]]></title>
            <link>https://medium.com/daily-python/python-script-to-merge-pdf-files-daily-python-28-54acdf5c0473?source=rss-633ba00874a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/54acdf5c0473</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[application]]></category>
            <category><![CDATA[daily-python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Ajinkya Sonawane]]></dc:creator>
            <pubDate>Thu, 13 Feb 2020 18:51:16 GMT</pubDate>
            <atom:updated>2020-02-13T18:51:16.271Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a tutorial on how to merge PDF files using Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwptYQ5vK-50iN2vbcMsGw.png" /></figure><blockquote>This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.</blockquote><h3>Requirements:</h3><ol><li>Python 3.0</li><li>Pip</li></ol><h3>Install the following packages:</h3><ol><li><a href="https://pypi.org/project/PyPDF2/">PyPDF2</a> — PDF toolkit based on Python</li></ol><pre>pip install PyPDF2</pre><h3>Let’s import the required modules</h3><pre>from os import listdir,mkdir,startfile<br>from os.path import isfile, join,exists<br>from PyPDF2 import PdfFileMerger</pre><ol><li>listdir — used to list the files in the given directory</li><li>mkdir — used to create a new directory</li><li>startfile — used to launch a file</li><li>isfile — used to check if an input is a file</li><li>join — used to join one or more path components intelligently</li><li>exists — used to check if a folder or file exists</li><li>PDFFileMerger — used to merge the pdf files</li></ol><h3>Let’s take the path from where the PDF files are to be fetched and print the file names</h3><pre>#Input file path and print the pdf files in that path<br>path = input(&quot;Enter the folder location: &quot;)<br>pdffiles = [f for f in listdir(path) if isfile(join(path, f)) and &#39;.pdf&#39; in f]<br>print(&#39;\nList of PDF Files:\n&#39;)<br>for file in pdffiles:<br>    print(file)</pre><h3>Accept the name of the result file</h3><pre>#Input the name of the result file<br>resultFile = input(&quot;\nEnter the name of the result file : &quot;)<br>if &#39;.pdf&#39; not in resultFile:<br>    resultFile += &#39;.pdf&#39;</pre><h3>Traverse through the pdf files and append them</h3><pre>#Append the pdf files<br>merger = PdfFileMerger()<br>for pdf in pdffiles:<br>    merger.append(path+&#39;\\&#39;+pdf)</pre><h3>Create an Output directory if none exists</h3><pre>#If the Output directory does not exist then create one<br>if not exists(path+&#39;\\Output&#39;):<br>    mkdir(path+&#39;\\Output&#39;)</pre><h3>Now, merge the files and write it to the output directory</h3><pre>#Write the merged result file to the Output directory<br>merger.write(path+&#39;\\Output\\&#39;+resultFile)<br>merger.close()</pre><h3>Finally, we launch the result file, a merged pdf of the given pdf files</h3><pre>#Launch the result file<br>print(&#39;\n&#39;+resultFile,&#39;Successfully created!!! at &#39;,path+&#39;\\Output\\&#39;)<br>startfile(path+&#39;\\Output\\&#39;+resultFile)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*QCWoMwhweYNh9_3Ai7JPtg.png" /><figcaption>The above code snippet in action</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*pGu_xKJzhla5WnoKmyoDog.png" /></figure><p><em>I hope this article was helpful, do leave some claps if you liked it.</em></p><h4>Follow the Daily Python Challenge here:</h4><ul><li><a href="https://github.com/Ajinkya-Sonawane/Daily-Python">Ajinkya-Sonawane/Daily-Python</a></li><li><a href="https://instagram.com/daily.py">Login * Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54acdf5c0473" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-python/python-script-to-merge-pdf-files-daily-python-28-54acdf5c0473">Python script to merge PDF Files | Daily Python #28</a> was originally published in <a href="https://medium.com/daily-python">Daily Python</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Fibonacci Search algorithm in Python | Daily Python #27]]></title>
            <link>https://medium.com/daily-python/implementing-fibonacci-search-algorithm-in-python-daily-python-27-4a6624366022?source=rss-633ba00874a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a6624366022</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[daily-python]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ajinkya Sonawane]]></dc:creator>
            <pubDate>Wed, 12 Feb 2020 18:19:33 GMT</pubDate>
            <atom:updated>2020-02-16T17:03:39.584Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Fibonacci Search algorithm in Python| Daily Python #27</h3><p>This article is a tutorial on implementing the Fibonacci Search algorithm in Python and is in continuation with Daily Python #21</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*pcG5U6TYpxy2Rmig.png" /></figure><blockquote>This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.</blockquote><blockquote>There are no additional requirements for this article.</blockquote><p>If you haven’t read Part 1 of basic searching algorithms then you can read it from here:</p><p><a href="https://medium.com/daily-python/implementing-basic-searching-algorithms-in-python-part-1-daily-python-21-70025990f2b6">Implementing basic searching algorithms in Python — Part 1 | Daily Python #21</a></p><h3>Fibonacci Search</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/0*YI7lHzN2UebiaV4g.png" /><figcaption>Source: GeeksForGeeks</figcaption></figure><p>Fibonacci Search is a comparison-based technique that uses Fibonacci numbers to search an element in a sorted array.</p><ol><li>Works for sorted arrays</li><li>A Divide and Conquer Algorithm.</li><li>Has Log n time complexity.</li></ol><h4><strong>Differences with Binary Search</strong>:</h4><ol><li>Fibonacci Search divides given array in unequal parts</li><li>Binary Search uses the division operator to divide range. Fibonacci Search doesn’t use /, but uses + and -. The division operator may be costly on some CPUs.</li><li>Fibonacci Search examines relatively closer elements in subsequent steps. So when the input array is big that cannot fit in CPU cache or even in RAM, Fibonacci Search can be useful.</li></ol><h4><strong>Background:</strong></h4><p>Fibonacci Numbers are recursively defined as F(n) = F(n-1) + F(n-2), F(0) = 0, F(1) = 1. First few Fibonacci Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …</p><h3>Let’s define a function to generate a Fibonacci number at the index of n</h3><pre>def FibonacciGenerator(n):<br>    if n &lt; 1:<br>        return 0<br>    elif n == 1:<br>        return 1<br>    else:<br>        return FibonacciGenerator(n - 1) + FibonacciGenerator(n - 2)</pre><h3>Let’s consider the following array and the number to be searched</h3><pre>arr = [10, 22, 30, 44, 56, 58, 60, 70, 100, 110, 130] <br>x = 60</pre><h3>Now, let’s define a function that will divide the list and search for the number as per the Fibonacci Search</h3><pre>def FibonacciSearch(arr, x):<br>    m = 0 <br>    while FibonacciGenerator(m) &lt; len(arr): # <br>        m = m + 1 <br>    offset = -1    <br>    while (FibonacciGenerator(m) &gt; 1):<br>        i = min( offset + FibonacciGenerator(m - 2) , len(arr) - 1)<br>        print(&#39;Current Element : &#39;,arr[i])<br>        if (x &gt; arr[i]):<br>            m = m - 1<br>            offset = i<br>        elif (x &lt; arr[i]):<br>            m = m - 2<br>        else:<br>            return i        <br>    if(FibonacciGenerator(m - 1) and arr[offset + 1] == x):<br>        return offset + 1<br>    return -1</pre><pre>print(&#39;Number found at index : &#39;,FibonacciSearch(arr, x))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*9wkWUUJaxpyWugnMftaQsQ.png" /><figcaption>Snip of the output of the above code snippet</figcaption></figure><p><em>I hope this article was helpful, do leave some claps if you liked it.</em></p><h4>Follow the Daily Python Challenge here:</h4><ul><li><a href="https://github.com/Ajinkya-Sonawane/Daily-Python">Ajinkya-Sonawane/Daily-Python</a></li><li><a href="https://instagram.com/daily.py">Login * Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a6624366022" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-python/implementing-fibonacci-search-algorithm-in-python-daily-python-27-4a6624366022">Implementing Fibonacci Search algorithm in Python | Daily Python #27</a> was originally published in <a href="https://medium.com/daily-python">Daily Python</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Python Bot that tweets inspirational quotes | Daily Python #26]]></title>
            <link>https://ajinkyasonawane.medium.com/building-a-python-bot-that-tweets-inspirational-quotes-daily-python-26-9906af4609a4?source=rss-633ba00874a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9906af4609a4</guid>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[daily-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ajinkya Sonawane]]></dc:creator>
            <pubDate>Tue, 11 Feb 2020 18:30:57 GMT</pubDate>
            <atom:updated>2021-01-15T16:41:00.743Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python script that tweets for you| Daily Python #26</h3><p>This article is a tutorial to build a bot that tweets inspirational quotes every minute using Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vi4wrqC_9cu1k7Iy.jpg" /></figure><blockquote>This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.</blockquote><h3>Requirements:</h3><ol><li>Python 3.0</li><li>Pip</li></ol><h3>Install the following packages:</h3><ol><li><a href="http://docs.tweepy.org/en/v3.5.0/">tweepy</a> — Library that provides easy access to Twitter APIs</li><li><a href="https://pypi.org/project/requests/">requests</a> — Library to making HTTP requests.</li><li>json — Library to handle JSON objects</li><li>time</li></ol><pre>pip install tweepy requests</pre><h3>Let’s import the required modules</h3><pre>import requests<br>import tweepy<br>import time<br>import json</pre><h3>The first step is to set up the Twitter Bot using ‘tweepy’</h3><p><strong>Note: </strong>Follow the instructions in the following article and create your app</p><p><a href="https://medium.com/daily-python/python-script-to-fetch-tweets-based-on-hashtags-daily-python-02-4ee26d7cefcc">Python script to fetch tweets based on hashtags(#)| Daily Python #2</a></p><p>After you have created your twitter application and generated the API Keys and Access tokens, define a function to set up the twitter bot.</p><pre>def setup_Bot():<br>    consumerKey = &quot;YOUR_API_KEY&quot;<br>    consumerSecret = &quot;YOUR_API_KEY_SECRET&quot;<br>    accessToken = &quot;YOUR_ACCESS_TOKEN&quot;<br>    accessTokenSecret = &quot;YOUR_ACCESS_TOKEN_SECRET&quot;<br>    auth = tweepy.OAuthHandler(consumerKey, consumerSecret)<br>    auth.set_access_token(accessToken, accessTokenSecret)<br>    api = tweepy.API(auth)<br>    return api</pre><h3>Now, let’s write a function that will fetch an inspirational quote for the bot</h3><p>The following API provides random inspirational quotes:</p><p><a href="https://forismatic.com/en/api/">Quotes and expressions. The most inspiring expressions of mankind.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*oS7g5bFktTplzEEEAQxVpA.png" /></figure><p>We need to make a call to this method in order to fetch a random inspirational quote for our twitter bot.</p><pre>def get_Quote():<br>    params = {<br>        &#39;method&#39;:&#39;getQuote&#39;,<br>        &#39;lang&#39;:&#39;en&#39;,<br>        &#39;format&#39;:&#39;json&#39;<br>    }<br>    res = requests.get(&#39;<a href="http://api.forismatic.com/api/1.0/&#39;,params">http://api.forismatic.com/api/1.0/&#39;,params</a>)<br>    jsonText =json.loads(response.text)<br>    return jsonText[&quot;quoteText&quot;],jsonText[&quot;quoteAuthor&quot;]</pre><p>Using the JSON module we can convert the response text to a JSON object and access its individual key-value pairs.</p><h3>Finally, let’s write a loop that will tweet an inspirational quote every minute</h3><pre>api = setup_Bot()<br>while True:<br>    try:<br>        quote,author = get_Quote()<br>        status = quote+&quot; -&quot;+author+&quot;\n&quot;+&quot;#python \<br>        #dailypython #twitterbot #pythonquotes #programming&quot;<br>        print(&#39;\nUpdating : &#39;,status)<br>        api.update_status(status=status)<br>        print(&quot;\nGoing to Sleep for 1 min&quot;)<br>        time.sleep(60)<br>    except Exception as ex:<br>        print(ex)<br>        break</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*CLe3dhNa2LpePKFACRZnWQ.png" /><figcaption>The output of the twitter bot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*7AIeQy_yy7GQf2-heBlyng.png" /><figcaption>Snip of the tweets posted by the bot</figcaption></figure><p>Modify this code and make your twitter bot do what you want. Read the terms and conditions given by twitter for developing twitter bots.</p><p>I hope this article was helpful, do leave some claps if you liked it.</p><h4>Follow the Daily Python Challenge here:</h4><ul><li><a href="https://github.com/Ajinkya-Sonawane/Daily-Python">Ajinkya-Sonawane/Daily-Python</a></li><li><a href="https://instagram.com/daily.py">Login * Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9906af4609a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python script to search flights using Goibibo API | Daily Python #25]]></title>
            <link>https://medium.com/daily-python/python-script-to-search-flights-using-goibibo-api-daily-python-25-eb08e30aaf33?source=rss-633ba00874a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb08e30aaf33</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[daily-python]]></category>
            <category><![CDATA[flight]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Ajinkya Sonawane]]></dc:creator>
            <pubDate>Mon, 10 Feb 2020 18:33:08 GMT</pubDate>
            <atom:updated>2020-02-10T18:33:08.732Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a tutorial on how to search for flights by consuming the Goibibo API in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*-teMAM7V6ZDIzHQ3" /></figure><h3>Requirements:</h3><ol><li>Python 3.0</li><li>Pip</li></ol><h3>Install the following packages:</h3><ol><li><a href="https://pypi.org/project/requests/">requests</a> — Library to making HTTP requests.</li><li>pprint — PrettyPrinter:</li></ol><pre>pip install requests pprint</pre><h3>First, let’s sign up on the Goibibo’s API portal</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGl_FD8IknV9Y12ys0O2Uw.png" /></figure><p>Fill in the details and activate your account from the email received. You will now be able to access the API key and the Application ID, which will be used for making calls with the APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XqpGA3Hnj6jkbUZDuwCNUg.png" /></figure><h3>First, let’s import the requests module</h3><pre>import requests<br>from pprint import PrettyPrinter<br>pp = PrettyPrinter()</pre><h3>Store the App ID and the API Key into variables for future use</h3><pre>AppID = &quot;YOUR_GOIBIBO_APP_ID&quot;<br>AppKey = &quot;YOUR_GOIBIBO_APP_KEY&quot;</pre><h3>The parameters required for fetching flights using the API</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTEWtSMpW7PB4i7M-3O8JQ.png" /></figure><h3>Let’s create a dictionary to store the values of these parameters</h3><pre>params = {<br>    &quot;app_id&quot;:AppID,<br>    &quot;app_key&quot;:AppKey,<br>    &quot;format&quot;:&quot;json&quot;,<br>    &quot;source&quot;:&quot;PNQ&quot;,<br>    &quot;destination&quot;:&quot;BOM&quot;,<br>    &quot;dateofdeparture&quot;:&quot;20200215&quot;,<br>    &quot;dateofarrival&quot;:&quot;&quot;,<br>    &quot;&quot;:&quot;&quot;,<br>    &quot;seatingclass&quot;:&quot;E&quot;,<br>    &quot;adults&quot;:&quot;1&quot;,<br>    &quot;children&quot;:&quot;0&quot;,<br>    &quot;counter&quot;:&quot;100&quot;,  <br>}</pre><h3>Let’s hit the API Url and fetch the result for the above parameters</h3><pre>URL = &quot;<a href="http://developer.goibibo.com/api/search/">http://developer.goibibo.com/api/search/</a>&quot;</pre><pre>response = requests.get(URL,params=params).json()<br>pp.pprint(response)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*tWNIRJYO-SExbiSaNQ90CQ.png" /><figcaption>Snip of the JSON Response (output) of the above code snippet</figcaption></figure><p>We can loop this code and try to find the best flight price for the given locations and then simply send an email reminder using the mail service which was discussed in <a href="https://medium.com/analytics-vidhya/python-script-to-track-amazon-prices-4b2610da5f49"><strong>Daily Python #1</strong></a>.</p><p>I hope this article was helpful, do leave some claps if you liked it.</p><h4>Follow the Daily Python Challenge here:</h4><ul><li><a href="https://github.com/Ajinkya-Sonawane/Daily-Python">Ajinkya-Sonawane/Daily-Python</a></li><li><a href="https://instagram.com/daily.py">Login * Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb08e30aaf33" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-python/python-script-to-search-flights-using-goibibo-api-daily-python-25-eb08e30aaf33">Python script to search flights using Goibibo API | Daily Python #25</a> was originally published in <a href="https://medium.com/daily-python">Daily Python</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interesting Python modules for Beginners | Daily Python #24]]></title>
            <link>https://medium.com/daily-python/interesting-python-modules-for-beginners-daily-python-24-dd73f47f5cf6?source=rss-633ba00874a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd73f47f5cf6</guid>
            <category><![CDATA[daily-python]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[articles]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ajinkya Sonawane]]></dc:creator>
            <pubDate>Thu, 30 Jan 2020 18:24:25 GMT</pubDate>
            <atom:updated>2020-01-30T18:24:25.164Z</atom:updated>
            <content:encoded><![CDATA[<p>This article lists a few interesting modules to play around whilst learning Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*cFbWWLBna01gQ4_9" /><figcaption>Source: Real Python</figcaption></figure><blockquote>This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.</blockquote><h3>Requirements:</h3><ol><li>Python 3.0</li><li>Pip</li></ol><h3>Install the following packages:</h3><ol><li><a href="https://pypi.org/project/pyperclip/">pyperclip </a>— Library to handle clipboard content</li><li><a href="https://pypi.org/project/emoji/">emoji </a>— Library to generate emojis</li><li><a href="https://pypi.org/project/howdoi/">howdoi </a>— Library to guide through python</li><li><a href="https://pypi.org/project/antigravity/">antigravity</a></li><li><a href="https://pypi.org/project/wikipedia/">wikipedia</a> — Library to fetch wikipedia content</li><li><a href="https://docs.python.org/3/library/dis.html">dis </a>— Library to uncover how Python works internally</li></ol><h3>Pyperclip</h3><p>I have discussed how to handle clipboard content using ‘pynput’. This library is an alternative to that and quite easy to implement. We just need to use the copy and paste functions to copy from or to write to the clipboard. Below is an example of how you can use ‘pyperclip’.</p><pre>#1. Pyperclip<br>import pyperclip<br>pyperclip.copy(&#39;Heyyy this is being copied to clipboard&#39;)<br>print(pyperclip.paste())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*iK26AoLEZoLSv91bDx0oKQ.png" /><figcaption>Snip of the Ouput of the above code snippet</figcaption></figure><h3>Emoji</h3><p>This library makes it easy to create emojis in Python. If you are building a chatbot and want to recommend emojis based on text, then you can suggest relevant emojis by applying regular expressions on the input string. The ‘emojize’ function returns the Unicode characters for the given emoji name.</p><pre>#2. Emoji<br>from emoji import emojize<br>print(emojize(&#39;:thumbs_up:&#39;),emojize(&#39;:snake:&#39;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*DElcCqLee36IUL4li4F9TQ.png" /><figcaption>The output of the above code snippet</figcaption></figure><h3>How Do I?</h3><p>This library is quite handy if you want to avoid going to google and searching for how to do a particular operation in Python. You can directly access this module through the terminal or you can import it in a Python script and pass the required query. The following code snippet demonstrates how to open a file in Python using ‘howdoi ’module.</p><pre>#3. Howdoi<br>from howdoi import howdoi<br>query = &quot;open a file in python&quot;<br>parser = howdoi.get_parser()<br>args = vars(parser.parse_args(query.split(&#39; &#39;)))<br>output = howdoi.howdoi(args)<br>print(output)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*FoqtGJ0BqwAfFTg1G4nP9A.png" /></figure><h3>Antigravity</h3><p>This library opens up a webpage that contains comics related to python. The reason this module is here is that this is quite fun! It’s basically an easter egg in Python 3 which is used in Google App Engines. It was added to Google App Engines just as a medium to amuse the users.</p><pre>#4. Antigravity<br>import antigravity</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*IcO-oFF0wtuzL52KvHq7LQ.png" /><figcaption>Snip of the webpage resulted by importing antigravity</figcaption></figure><h3>Wikipedia</h3><p>As the name suggests, this module is built to easily access Wikipedia pages from Python. If you are building an application that needs to access Wikipedia pages, then this module is quite handy and easy to integrate into any application. You can also get the summary of the page by using the summary attribute of the Wikipedia page.</p><pre>#5. Wikipedia<br>import wikipedia<br>page = wikipedia.page(&quot;Python&quot;)<br>print(page.summary)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_Vg_lv1hmvVKdD0GQyUlg.png" /></figure><h3>Dissembler Python</h3><p>In simple terms, this module shows what happens under the hood of the Python interpreter. The dis module supports the analysis of CPython bytecode by disassembling it. The CPython bytecode which this module takes as an input is defined in the file Include/opcode.h and used by the compiler and the interpreter.</p><p>CPython implementation detail: Bytecode is an implementation detail of the CPython interpreter. No guarantees are made that bytecode will not be added, removed, or changed between versions of Python. The use of this module should not be considered to work across Python VMs or Python releases.</p><pre>#6. Dissemble Python<br>import dis<br>def myfun(num):<br>    return(&#39;Number to string : &#39;,str(num))</pre><pre>dis.dis(myfun)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*Y5ZDi-4FdWjEvnDSvlEhHA.png" /><figcaption>Snip of the output of the above code snippet</figcaption></figure><p><em>I hope this article was helpful, do leave some claps if you liked it.</em></p><h4>Follow the Daily Python Challenge here:</h4><ul><li><a href="https://github.com/Ajinkya-Sonawane/Daily-Python">Ajinkya-Sonawane/Daily-Python</a></li><li><a href="https://instagram.com/daily.py">Login * Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd73f47f5cf6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-python/interesting-python-modules-for-beginners-daily-python-24-dd73f47f5cf6">Interesting Python modules for Beginners | Daily Python #24</a> was originally published in <a href="https://medium.com/daily-python">Daily Python</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Decision Tree Classifier using Python | Daily Python #23]]></title>
            <link>https://medium.com/daily-python/simple-decision-tree-classifier-using-python-daily-python-23-205635ac365d?source=rss-633ba00874a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/205635ac365d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[daily-python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ajinkya Sonawane]]></dc:creator>
            <pubDate>Wed, 29 Jan 2020 16:41:25 GMT</pubDate>
            <atom:updated>2020-01-29T16:41:25.218Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is a tutorial on how to implement a decision tree classifier using Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*4bzPZsKW-by_umbK.jpg" /></figure><blockquote>This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.</blockquote><h3>Requirements:</h3><ol><li>Python 3.0</li><li>Pip</li></ol><h3>Install the following packages:</h3><ol><li><a href="https://pandas.pydata.org/">pandas </a>— BSD-licensed library providing high-performance, easy-to-use data structures, and data analysis tools.</li><li><a href="https://scikit-learn.org/stable/index.html">sklearn </a>— provides dozens of built-in machine learning algorithms and models</li><li><a href="https://pypi.org/project/graphviz/">graphviz</a>— facilitates the creation, and rendering of graph descriptions in the <a href="https://www.graphviz.org/doc/info/lang.html">DOT</a> language</li></ol><h3>What is a Classifier?</h3><p>According to Wikipedia — An algorithm that implements classification, especially in a concrete implementation, is known as a classifier. The term “classifier” sometimes also refers to the mathematical function, implemented by a classification algorithm, that maps input data to a category.</p><h3>Then, what is a Decision Tree?</h3><p>A <strong>decision tree</strong> is a decision support tool that uses a tree-like model of decisions and their possible consequences, including chance event outcomes, resource costs, and utility. It is one way to display an algorithm that only contains conditional control statements.</p><p>A decision tree consists of three types of nodes:</p><ol><li>Decision nodes — typically represented by squares</li><li>Chance nodes — typically represented by circles</li><li>End nodes — typically represented by triangles</li></ol><p>A Decision Tree Classifier classifies a given data into different classes depending on the tree developed using the training data.</p><h3>Advantages of decision trees</h3><p>Among decision support tools, decision trees (and influence diagrams) have several advantages. Decision trees:</p><ul><li>Are simple to understand and interpret. People are able to understand decision tree models after a brief explanation.</li><li>Have value even with little hard data. Important insights can be generated based on experts describing a situation (its alternatives, probabilities, and costs) and their preferences for outcomes.</li><li>Help determine worst, best and expected values for different scenarios.</li><li>Use a <a href="https://en.wikipedia.org/wiki/White_box_(software_engineering)">white-box</a> model. If a given result is provided by a model.</li><li>It can be combined with other decision techniques.</li></ul><h3>Disadvantages of decision trees:</h3><ul><li>They are unstable, meaning that a small change in the data can lead to a large change in the structure of the optimal decision tree.</li><li>They are often relatively inaccurate. Many other predictors perform better with similar data. This can be remedied by replacing a single decision tree with a random forest of decision trees, but a random forest is not as easy to interpret as a single decision tree.</li><li>For data including categorical variables with a different number of levels, information gain in decision trees is biased in favor of those attributes with more levels.</li><li>Calculations can get very complex, particularly if many values are uncertain and/or if many outcomes are linked.</li></ul><p><a href="https://medium.com/machine-learning-101/chapter-3-decision-trees-theory-e7398adac567">Chapter 3 : Decision Tree Classifier — Theory</a></p><p>Go through the above article for a detailed explanation of the Decision Tree Classifier and the various methods which can be used to build a decision tree.</p><h3>What is Sci-kit Learn?</h3><p><strong>Scikit-learn</strong> (formerly <strong>scikits.learn</strong> and also known as <strong>sklearn</strong>) is a free software machine learning library for the Python programming language. It features various classification, regression and clustering algorithms including support vector machines, random forests, gradient boosting, <em>k</em>-means and DBSCAN, and is designed to interoperate with the Python numerical and scientific libraries NumPy and SciPy.</p><h3>Data that we will be using for classification</h3><p><a href="https://www.capitalbikeshare.com/system-data">Capital Share</a> — Capital Bikeshare is metro DC’s bike-share service, with 4,300 bikes and 500+ stations across 7 jurisdictions: Washington, DC.; Arlington, VA; Alexandria, VA; Montgomery, MD; Prince George’s County, MD; Fairfax County, VA; and the City of Falls Church, VA. Designed for quick trips with convenience in mind, it’s a fun and affordable way to get around.</p><h3>Trip History Data</h3><p>Each quarter, we publish <a href="https://s3.amazonaws.com/capitalbikeshare-data/index.html">downloadable files</a> of Capital Bikeshare trip data. The data includes:</p><ul><li>Duration — Duration of trip</li><li>Start Date — Includes start date and time</li><li>End Date — Includes end date and time</li><li>Start Station — Includes starting station name and number</li><li>End Station — Includes ending station name and number</li><li>Bike Number — Includes ID number of bike used for the trip</li><li>Member Type — Indicates whether user was a “registered” member (Annual Member, 30-Day Member or Day Key Member) or a “casual” rider (Single Trip, 24-Hour Pass, 3-Day Pass or 5-Day Pass)</li></ul><p>This data has been processed to remove trips that are taken by staff as they service and inspect the system, trips that are taken to/from any of our “test” stations at our warehouses and any trips lasting less than 60 seconds (potentially false starts or users trying to re-dock a bike to ensure it’s secure).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8EOoWxJnPbJOh8jbEoaIQ.png" /><figcaption>Snip of the data being used</figcaption></figure><h3>Import the required libraries</h3><pre># Importing the required packages <br>import numpy as np <br>import pandas as pd <br>from sklearn.metrics import confusion_matrix <br>from sklearn.model_selection import train_test_split <br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn import tree<br>from sklearn.metrics import accuracy_score <br>from sklearn.metrics import classification_report <br>import graphviz</pre><h3>Function to import the data from the CSV file</h3><pre># Function importing Dataset <br>def importdata(): <br> balance_data = pd.read_csv(&#39;capitalshare.csv&#39;) <br> balance_data = balance_data[[&#39;Duration&#39;,&#39;Start station number&#39;,&#39;End station number&#39;,&#39;Member type&#39;]]<br> #print(balance_data)<br> # Printing the dataswet shape <br> print (&quot;Dataset Lenght: &quot;, len(balance_data)) <br> print (&quot;Dataset Shape: &quot;, balance_data.shape) <br> <br> # Printing the dataset obseravtions <br> print (&quot;Dataset: &quot;,balance_data.head()) <br> return balance_data</pre><h3>Function to split the data into training and test data</h3><pre># Function to split the dataset <br>def splitdataset(balance_data):</pre><pre># Seperating the target variable <br> X = balance_data.values[:, :-1] <br> Y = balance_data.values[:, -1]</pre><pre># Spliting the dataset into train and test <br> X_train, X_test, y_train, y_test = train_test_split( <br> X, Y, test_size = 0.3, random_state = 100) <br> <br> return X_train, X_test, y_train, y_test</pre><h3>Function to visualize the developed tree model</h3><pre>#Function to visualize tree<br>def visualize_tree(data,clf,clf_name):<br> features = data.columns<br> features = features[:-1]<br> class_names = list(set(data.iloc[:,-1]))<br> dot_data = tree.export_graphviz(clf, out_file=None,  \<br>  feature_names=features,class_names=class_names,  \<br>  filled=True, rounded=True, special_characters=True)<br> graph = graphviz.Source(dot_data)<br> graph.render(&#39;dtree_render_&#39;+clf_name,view=True)</pre><h3>Function to train the decision tree using Gini Index</h3><pre># Function to perform training with giniIndex. <br>def train_using_gini(X_train, X_test, y_train,data):</pre><pre># Creating the classifier object <br> clf_gini = DecisionTreeClassifier(criterion = &quot;gini&quot;, <br>   random_state = 100,max_depth=3, min_samples_leaf=5)<br>        # Performing training <br> clf_gini.fit(X_train, y_train)<br> visualize_tree(data,clf_gini,&#39;gini&#39;)<br> print(&#39;\nFeature Importance : &#39;,clf_gini.feature_importances_)<br> return  clf_gini</pre><h3>Function to train the decision tree using Entropy</h3><pre># Function to perform training with entropy. <br>def tarin_using_entropy(X_train, X_test, y_train,data):</pre><pre># Decision tree with entropy <br> clf_entropy = DecisionTreeClassifier( <br>   criterion = &quot;entropy&quot;, random_state = 100, <br>   max_depth = 3, min_samples_leaf = 5)</pre><pre># Performing training <br> clf_entropy.fit(X_train, y_train)<br> visualize_tree(data,clf_entropy,&#39;entropy&#39;)<br> print(&#39;\nFeature Importance : &#39;,clf_entropy.feature_importances_)<br> return clf_entropy</pre><h3>Function to predict the class after training</h3><pre># Function to make predictions <br>def prediction(X_test, clf_object):</pre><pre># Predicton on test with giniIndex <br> y_pred = clf_object.predict(X_test) <br> print(&quot;Predicted values:&quot;) <br> print(y_pred) <br> return y_pred</pre><h3>Function to calculate accuracy</h3><pre># Function to calculate accuracy <br>def cal_accuracy(y_test, y_pred): <br> <br> print(&quot;Confusion Matrix: &quot;, <br>  confusion_matrix(y_test, y_pred)) <br> <br> print (&quot;Accuracy : &quot;, <br> accuracy_score(y_test,y_pred)*100) <br> <br> print(&quot;Report : &quot;, <br> classification_report(y_test, y_pred))</pre><h3>Main Process</h3><pre># Main process   <br>def main(): <br> <br> # Building Phase <br> data = importdata() <br> X_train, X_test, y_train, y_test = splitdataset(data) <br> clf_gini = train_using_gini(X_train, X_test, y_train,data) <br> clf_entropy = tarin_using_entropy(X_train, X_test, y_train,data) <br> <br> # Operational Phase <br> print(&quot;Results Using Gini Index:&quot;) <br> <br> # Prediction using gini <br> y_pred_gini = prediction(X_test, clf_gini) <br> cal_accuracy(y_test, y_pred_gini) <br> <br> print(&quot;Results Using Entropy:&quot;) <br> # Prediction using entropy <br> y_pred_entropy = prediction(X_test, clf_entropy) <br> cal_accuracy(y_test, y_pred_entropy) <br> <br> <br># Calling main function <br>if __name__==&quot;__main__&quot;: <br> main()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*0nSVoIUMD5KCin3BRRUcIw.png" /><figcaption>Snip of the output of the above code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lnNQhYlx64CuGIkQBxaFw.png" /><figcaption>Decision Tree built using Gini Index</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNLCv43RPCubKaOtj5h_8A.png" /><figcaption>Decision Tree built using Entropy</figcaption></figure><p><em>I hope this article was helpful, do leave some claps if you liked it.</em></p><h4>Follow the Daily Python Challenge here:</h4><ul><li><a href="https://github.com/Ajinkya-Sonawane/Daily-Python">Ajinkya-Sonawane/Daily-Python</a></li><li><a href="https://instagram.com/daily.py">Login * Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=205635ac365d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-python/simple-decision-tree-classifier-using-python-daily-python-23-205635ac365d">Simple Decision Tree Classifier using Python | Daily Python #23</a> was originally published in <a href="https://medium.com/daily-python">Daily Python</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python script to block Websites !!! | Daily Python #22]]></title>
            <link>https://medium.com/daily-python/python-script-to-block-websites-daily-python-22-ce53c68416ca?source=rss-633ba00874a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce53c68416ca</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[daily-python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <dc:creator><![CDATA[Ajinkya Sonawane]]></dc:creator>
            <pubDate>Tue, 28 Jan 2020 14:55:39 GMT</pubDate>
            <atom:updated>2020-01-28T14:57:14.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python script to block Websites !!! | Daily Python #22</h3><p>This article is a tutorial on how to block websites in a given time frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*G3oi0kygCI1f33Rl.png" /></figure><blockquote>This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.</blockquote><h3>Requirements:</h3><ol><li>Python 3.0</li><li>Pip</li></ol><h3>First, let’s find the hosts file stored by the operating system</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHnfMuZGkdK73iHBG8ekiA.png" /><figcaption>Path to the hosts file in Windows</figcaption></figure><h3>Content of the ‘hosts’ file</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgHKUZhoW6jbc0iglaPoeA.png" /><figcaption>Snip of the contents of the hosts file</figcaption></figure><h3>What is the ‘hosts’ file?</h3><p>The host is an operating system file that maps hostnames to IP addresses. In this program, we will be mapping hostnames of websites to our localhost address. Using python file handling manipulation we will write the hostname in hosts.txt and remove the lines after your working hours.</p><p>Note: The location of the host file may be different for different operating systems. Windows Users should create a copy of this hosts file.</p><h3>Let’s write the Python script that will do the task</h3><pre># Run this script as Administrator<br>import time <br>from datetime import datetime as dt</pre><pre>hostsFilePath = &quot;C:\\Windows\\System32\\drivers\\etc\\hosts&quot;<br># localhost&#39;s IP Address <br>redirect_IP = &quot;127.0.0.1&quot;</pre><pre># Websites that you want to block <br>website_list =[&quot;<a href="http://www.facebook.com">www.facebook.com</a>&quot;,&quot;facebook.com&quot;, <br>  &quot;<a href="http://www.gmail.com">www.gmail.com</a>&quot;,&quot;gmail.com&quot;]</pre><pre>while True: <br> # time of your work <br> if dt(dt.now().year, dt.now().month, dt.now().day,8) \<br> &lt; dt.now() &lt; dt(dt.now().year, dt.now().month, dt.now().day,21): <br>  with open(hostsFilePath, &#39;r+&#39;) as file: <br>   content = file.read() <br>   for website in website_list: <br>    if website in content: <br>     pass<br>    else: <br>     # Mapping hostnames to be blocked to your localhost IP address <br>     file.write(redirect_IP + &quot; &quot; + website + &quot;\n&quot;) <br>     print(&quot;Access Denied...&quot;) <br> else: <br>  with open(hostsFilePath, &#39;r+&#39;) as file: <br>   content=file.readlines() <br>   file.seek(0) <br>   for line in content: <br>    if not any(website in line for website in website_list): <br>     file.write(line) <br>   # Removing hostnmes from hosts file <br>   file.truncate() <br>  print(&quot;Access Granted...&quot;) <br> time.sleep(5)</pre><p>Change the extension of the Python file from ‘.py’ to ‘.pyw’ and run the script as Administrator to gain access to the hosts file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0LSZ9ld9us8iXkDsHSyegA.png" /><figcaption>Gmail blocked by the Python script</figcaption></figure><h3>You can also, schedule the above script to run At startup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*7k-QuyrUL7D74DQMWg3udA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*a7KDzfcdvmhL-WvpImqeBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*GS-eywKwIUxW9En2VZglDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*-hU8ojH6cKicrXeAjKKjpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*TdteCO97w2gF6j19V3jd2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*oBllOvcmJ44ysJzEAz1EUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*VF7pDfSdaQhEGkVfYWt4MQ.png" /></figure><p>Finally, Restart your machine, and check if the website blocker works.</p><p><em>I hope this article was helpful, do leave some claps if you liked it.</em></p><h4>Follow the Daily Python Challenge here:</h4><ul><li><a href="https://github.com/Ajinkya-Sonawane/Daily-Python">Ajinkya-Sonawane/Daily-Python</a></li><li><a href="https://instagram.com/daily.py">Login * Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce53c68416ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-python/python-script-to-block-websites-daily-python-22-ce53c68416ca">Python script to block Websites !!! | Daily Python #22</a> was originally published in <a href="https://medium.com/daily-python">Daily Python</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing basic searching algorithms in Python — Part 1 | Daily Python #21]]></title>
            <link>https://medium.com/daily-python/implementing-basic-searching-algorithms-in-python-part-1-daily-python-21-70025990f2b6?source=rss-633ba00874a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/70025990f2b6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[searching]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[daily-python]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ajinkya Sonawane]]></dc:creator>
            <pubDate>Mon, 27 Jan 2020 09:19:52 GMT</pubDate>
            <atom:updated>2020-01-27T09:19:52.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing basic searching algorithms in Python — Part 1 | Daily Python #21</h3><p>This article is a tutorial on implementing basic searching algorithms in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*vAMvqZm-XbExtCpO.png" /></figure><blockquote>This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.</blockquote><blockquote>There are no additional requirements for this article.</blockquote><h3>Searching Algorithms</h3><p>Search algorithms form an important part of many programs. Some searches involve looking for an entry in a database, such as looking up your record in the IRS database. Other search algorithms trawl through a virtual space, such as those hunting for the best chess moves. Although programmers can choose from numerous search types, they select the algorithm that best matches the size and structure of the database to provide a user-friendly experience.</p><p>The general searching problem can be described as follows: Locate an element x in a list of distinct elements a1,a2,...an or determine that it is not in the list. The solution to this search problem is the location of the term in the list that equals x and is 0 if x is not in the list.</p><h3>Linear Search</h3><p>The linear search is the algorithm of choice for short lists, because it’s simple and requires minimal code to implement. The linear search algorithm looks at the first list item to see whether you are searching for it and, if so, you are finished. If not, it looks at the next item and on through each entry in the list.</p><h3>Working of Linear Search</h3><p>Linear search is the basic search algorithm used in data structures. It is also called as sequential search. Linear search is used to find a particular element in an array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*-X3ylnuSyKDzhqYP.png" /><figcaption>Source: GeeksforGeeks</figcaption></figure><h3>Let’s write a function to accept a sequence of numbers</h3><pre>def acceptSeq(order=&quot;random&quot;):<br>  seq = list(map(int,input(&quot;Enter a &quot;+order+&quot; sequence of numbers : &quot;).split(&quot; &quot;)))<br>  val = int(input(&quot;Enter the value to be serached : &quot;))<br>  return seq ,val</pre><h3>Now, let’s define a function to perform Linear Search</h3><pre>def acceptSeq(order=&quot;random&quot;):<br>  seq = list(map(int,input(&quot;Enter a &quot;+order+&quot; sequence of numbers : &quot;).split(&quot; &quot;)))<br>  val = int(input(&quot;Enter the value to be serached : &quot;))<br>  return seq ,val</pre><pre>def linearSearch(seql,val):<br>  for index in range(0,len(seq)):<br>    print(&#39;Current Index : &#39;,index,\<br>&#39;Value at this index : &#39;,seq[index])</pre><pre>if seq[index] == val:<br>      print(&#39;Number found at index : &#39;,index)<br>      return<br>  print(&#39;Number not found&#39;)</pre><pre>seq, val = acceptSeq()<br>linearSearch(seq,val)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*9tv2XTKJYsZKODZ20MOIww.png" /><figcaption>Snip of the Output of the above code snippet</figcaption></figure><h3>Binary Search</h3><p>Binary Search is one of the most fundamental and useful algorithms in Computer Science. It describes the process of searching for a specific value in an ordered collection.</p><p>Binary search is a popular algorithm for large databases with records ordered by numerical key. Example candidates include the IRS database keyed by social security number and the DMV records keyed by driver’s license numbers. The algorithm starts at the middle of the database — if your target number is greater than the middle number, the search will continue with the upper half of the database. If your target number is smaller than the middle number, the search will continue with the lower half of the database. It keeps repeating this process, cutting the database in half each time until it finds the record. This search is more complicated than the linear search but for large databases it’s much faster than a linear search.</p><h3>Working of Binary Search</h3><p>In its simplest form, Binary Search operates on a contiguous sequence with a specified left and right index. This is called the Search Space. Binary Search maintains the left, right, and middle indices of the search space and compares the search target or applies the search condition to the middle value of the collection; if the condition is unsatisfied or values unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful. If the search ends with an empty half, the condition cannot be fulfilled and target is not found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U4h5FGeXN_P5YwVP.png" /><figcaption>Source: GeeksforGeeks</figcaption></figure><h3>Let’s define a function to perform Binary Search</h3><pre>def binarySearch(seq,val):<br>  start,end = 0,len(seq)-1<br>  while start &lt;= end:<br>    mid = int((start+end)/2)<br>    print(&#39;Current Index : &#39;,mid,\<br>          &#39;Value at this index : &#39;,seq[mid])<br>    if seq[mid] == val:<br>      print(&#39;Number found at index : &#39;,mid)<br>      return<br>    elif val &gt; seq[mid]:<br>      start = mid+1<br>    elif val &lt; seq[mid]:<br>      end = mid-1<br>  print(&#39;Number not found &#39;)</pre><pre>seq, val = acceptSeq(order=&quot;sorted&quot;)<br>binarySearch(seq,val)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*GBq5e7b57PW0VW0MBZPgbA.png" /><figcaption>Snip of the Output of the above code snippet</figcaption></figure><h3>Exponential Search</h3><p>Exponential search is also known as doubling or galloping search. This mechanism is used to find the range where the search key may present. If L and U are the upper and lower bound of the list, then L and U both are the power of 2. For the last section, the U is the last position of the list. For that reason, it is known as exponential.</p><h3>Working of Exponential Search</h3><p>Exponential search allows for searching through a sorted, unbounded list for a specified input value (the search “key”). The algorithm consists of two stages. The first stage determines a range in which the search key would reside if it were in the list. In the second stage, a binary search is performed on this range. In the first stage, assuming that the list is sorted in ascending order, the algorithm looks for the first exponent, <em>j</em>, where the value 2j is greater than the search key. This value, 2j becomes the upper bound for the binary search with the previous power of 2, 2j — 1, being the lower bound for the binary search</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*hWytRLKHCQDZ6gHa.png" /><figcaption>Source: wikiwand</figcaption></figure><h3>Let’s define a function to perform Exponential Search</h3><pre>def exponentialSearch(seq,val):<br>  index = 1<br>  if seq[0] == val:<br>    print(&#39;Number found at index : 0&#39;)<br>    return<br>  while index &lt; len(seq) and seq[index] &lt; val:<br>    print(&#39;Current Index : &#39;,index)<br>    index = index * 2<br>    print(index)<br>  binarySearch(seq,val)</pre><pre>def breadthFirstSearch():<br>  pass</pre><pre>def depthFirstSearch():<br>  pass</pre><pre>seq, val = acceptSeq(order=&quot;sorted&quot;)<br>exponentialSearch(seq,val)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*UJi-aMVF07M7GzZV7NB_RQ.png" /><figcaption>Snip of the Output of the above code snippet</figcaption></figure><p><em>I hope this article was helpful, do leave some claps if you liked it.</em></p><h4>Follow the Daily Python Challenge here:</h4><ul><li><a href="https://github.com/Ajinkya-Sonawane/Daily-Python">Ajinkya-Sonawane/Daily-Python</a></li><li><a href="https://instagram.com/daily.py">Login * Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70025990f2b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-python/implementing-basic-searching-algorithms-in-python-part-1-daily-python-21-70025990f2b6">Implementing basic searching algorithms in Python — Part 1 | Daily Python #21</a> was originally published in <a href="https://medium.com/daily-python">Daily Python</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Pygame Basics — Part 1 | Daily Python #20]]></title>
            <link>https://medium.com/daily-python/introduction-to-pygame-basics-part-1-daily-python-20-69374c1b26f1?source=rss-633ba00874a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/69374c1b26f1</guid>
            <category><![CDATA[daily-python]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ajinkya Sonawane]]></dc:creator>
            <pubDate>Sun, 26 Jan 2020 12:07:43 GMT</pubDate>
            <atom:updated>2020-01-26T12:07:43.692Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Pygame Basics — Part 1 | Daily Python #20</h3><p>This article is an introduction to the Pygame module basics — Image load, movement, and key presses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*nr8xfIriulC1eIkW.png" /></figure><h3>Requirements:</h3><ol><li>Python 3.0</li><li>Pip</li></ol><h3>Install the following packages:</h3><ol><li><a href="https://www.pygame.org/docs/">pygame</a> — Library for making multimedia applications like games</li></ol><pre>pip install pygame</pre><h3>What is Pygame?</h3><p>is a Free and Open Source <a href="https://www.python.org/">python</a> programming language library for making multimedia applications like games built on top of the excellent <a href="http://www.libsdl.org/">SDL</a> library. Like SDL, pygame is highly portable and runs on nearly every platform and operating system. Millions of people have downloaded pygame itself, which is a whole lot of bits flying across the interwebs.</p><h3>Is Python suitable for gaming?</h3><p>It depends on the game. Python is actually quite capable of running games. It will likely even surprise you how much is possible in under 30 milliseconds. Still, it is not hard to reach the ceiling once your game begins to get more complex. Any game running in realtime will be making full use of the computer.</p><p>Over the past several years there has been an interesting trend in game development, the move towards higher-level languages. Usually, a game is split into two major parts. The game engine, which must be as fast as possible, and the game logic, which makes the engine actually do something. It wasn’t long ago when the engine of a game was written in assembly, with portions are written in C. Nowadays, C has moved to the game engine, while often the game itself is written in higher-level scripting languages. Games like Quake3 and Unreal run these scripts as portable bytecode. More recently, Python has been used in a variety of games like Freedom Force, and Humungous’ Backyard Sports Series.</p><p>Pygame is fairly low-level when it comes to writing games. You’ll quickly find yourself needing to wrap common functions into your own game environment. The great thing about this is there is nothing inside pygame to get in your way. Your program is in full control of everything. The side effect of that is you will find yourself borrowing a lot of code to get a more advanced framework put together. You’ll need a better understanding of what you are doing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*SW-WzK25t2DYrdGa6IZsOw.png" /><figcaption>Source: pygame.org</figcaption></figure><h3>Article’s Goal: Ball Control using Arrow Keys</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3KmbzQZ_XHXPo35wqhA27w.gif" /><figcaption>Ball Control using Arrow Keys</figcaption></figure><h3>Let’s import the required pygame module and initialize it</h3><pre>import pygame<br>pygame.init()</pre><h3>Let’s store some required measurements in variables</h3><pre>size = width,height = 500,500<br>color = (0,0,0)<br>vel = [2,2]<br>title = &quot;First Py-Game&quot;</pre><h3>Initialize the window/screen which will run the game</h3><pre>window = pygame.display.set_mode(size)<br>pygame.display.set_caption(title)</pre><h3>Download a ball icon with a transparent background</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*Hdzy2na1iXOZvdMkotF0-w.png" /></figure><h3>Import the ball and map it with a pygame’s rectangle object</h3><pre>ball = pygame.image.load(&quot;ball.png&quot;)<br>ballRect = ball.get_rect()</pre><p><strong>pygame.image.load(“ball.png”) </strong>— function returns us a Surface with the ball data. The Surface will keep any color-key or alpha transparency from the file. After loading the ball image we create a variable named ‘<strong>ballRect’</strong>. Pygame comes with a convenient utility object type named Rect, which represents a rectangular area.</p><h3>Now we define an infinite loop which will keep the window open till we don’t explicitly exit</h3><pre>run = True<br>while run:<br>    #Reset the pos <br>    pos = 0,0<br>    pygame.time.delay(100)<br>    print(pygame.event.get())<br>    #Handle Arrow Key event<br>    keys = pygame.key.get_pressed()<br>    if keys[pygame.K_LEFT]:<br>        pos = -10,0<br>    if keys[pygame.K_RIGHT]:<br>        pos = 10,0<br>    if keys[pygame.K_UP]:<br>        pos = 0,-10<br>    if keys[pygame.K_DOWN]:<br>        pos = 0,10<br>    #Break the loop when ESCAPE is pressed<br>    if keys[pygame.K_ESCAPE]:<br>        run = False<br>    #Move the rectangle<br>    ballRect = ballRect.move(pos)<br>    window.fill(color)<br>    window.blit(ball,ballRect)<br>    pygame.display.flip()</pre><pre>pygame.quit()</pre><p>This article is a basic introduction to pygame and does not consider the boundaries where the ball can be moved. Boundaries and obstacles will be covered in future articles.</p><p><em>I hope this article was helpful, do leave some claps if you liked it.</em></p><h4>Follow the Daily Python Challenge here:</h4><ul><li><a href="https://github.com/Ajinkya-Sonawane/Daily-Python">Ajinkya-Sonawane/Daily-Python</a></li><li><a href="https://instagram.com/daily.py">Login * Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69374c1b26f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/daily-python/introduction-to-pygame-basics-part-1-daily-python-20-69374c1b26f1">Introduction to Pygame Basics — Part 1 | Daily Python #20</a> was originally published in <a href="https://medium.com/daily-python">Daily Python</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>