<?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 Evangelos Zafeiratos on Medium]]></title>
        <description><![CDATA[Stories by Evangelos Zafeiratos on Medium]]></description>
        <link>https://medium.com/@ev.zafeiratos?source=rss-bd0ceda7f600------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZbXI6buCFBSxGlg8D5qnAw.png</url>
            <title>Stories by Evangelos Zafeiratos on Medium</title>
            <link>https://medium.com/@ev.zafeiratos?source=rss-bd0ceda7f600------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 21:44:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ev.zafeiratos/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[Sudoku Solver with Python : a methodical approach for algorithm optimization[part 2]]]></title>
            <link>https://medium.com/@ev.zafeiratos/sudoku-solver-with-python-a-methodical-approach-for-algorithm-optimization-part-2-c48e83b89d20?source=rss-bd0ceda7f600------2</link>
            <guid isPermaLink="false">https://medium.com/p/c48e83b89d20</guid>
            <category><![CDATA[sudoku]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[optimization-algorithms]]></category>
            <dc:creator><![CDATA[Evangelos Zafeiratos]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 13:44:50 GMT</pubDate>
            <atom:updated>2022-02-20T01:58:19.527Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/b2c99887167f?source=post_stats_page----------------------------------------">Sudoku Solver with Python : a methodical approach for algorithm optimization[part 2]</a></h3><p>This is the second of a series of articles dedicated to the popular game of Sudoku. More particularly, how we can build a script to automatically solve Sudoku puzzles with recursion and consequently improve its performance.</p><p>This second article intends to demonstrate the thinking process for optimizing the brute force solution that we used for our Sudoku solver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*j8MPSdY8HnPGoe8vIlbOCw.gif" /><figcaption>Demo of backtracking Algorithm</figcaption></figure><p>In the previous article the backtracking algorithm was introduced to solve the Sudoku by iterating through all possible values for each cell until there was no conflict between the new value introduced to the board and the values of cells belonging to same row, column or block.<br>This solution, however efficient, is far from optimal as it does not make use of any of the information provided by the board.</p><h3>Optimize by eliminating unnecessary iterations</h3><p>First idea for optimizing our code comes from the observation that our algorithm iterates through all numbers 1 to 9 sequentially (row 9) until it finds a value that does not conflict with another cell in the same row, column or block already containing the same value. However, the board gives us already some information on which numbers could not be possibly added in a certain cell.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96e07d2a7714741786eaa183738ebfc1/href">https://medium.com/media/96e07d2a7714741786eaa183738ebfc1/href</a></iframe><p>The idea is to scan our board upfront, save all the legitimate values for each cell in a memory and iterate through them instead of iterating through all numbers. <br>The following graphic demonstrates the set of allowed values for 2 cells of the board. As it is implied from the game rules every row, column and block cannot contain the same number more than once, thus all numbers found in cells belonging in the same row, column and block of a given cell are excluded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*_wSrFns5RRgVa6BEm8KEQg.gif" /><figcaption>Legitimate values for 2 board cells</figcaption></figure><p>Now that our idea is clear we are moving to the implementation with our code. We will be creating 2 functions for this task:</p><ol><li>Our enabler function which initializes the data structure (dictionary) to save the values and by iterating through the cells of the board, identifies the empty ones and calls our second function to actually execute the conditions that we described.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a0de42bfa2009828e59980d4b8f5e3c/href">https://medium.com/media/6a0de42bfa2009828e59980d4b8f5e3c/href</a></iframe><p>2. The allowedValues() function which has similar logic with isValid() function that we saw in Part 1, however in this case it extracts for each cell a list of legitimate numbers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fd02232f7de4e363ca9219f4485a420/href">https://medium.com/media/7fd02232f7de4e363ca9219f4485a420/href</a></iframe><p>Having our cache dictionary in place, we are ready to test whether this will be giving a significant boost to our program performance.</p><p>We need to replace the solve() function as well with a new function solveWithCache() which is expecting the dictionary cache in its parameters list and this time iterates only through the list of legitimate values for each cell instead of all numbers 1–9.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86a3188aeca705b77a17f6e17489e8d0/href">https://medium.com/media/86a3188aeca705b77a17f6e17489e8d0/href</a></iframe><p>Testing our code after implementing all the changes is providing us the desired results, a respectable drop in execution time compared to our first version:</p><blockquote>The execution time of above program is : 15.41820478439331 s</blockquote><h3>Optimize by adding information to our program</h3><p>Switching from a costly iteration to a pre-selected cache of values is a good step forward, but there is still a lot to be done to optimize our algorithm.</p><p>There is much information on the Sudoku board that has not been integrated yet into our algorithm logic:</p><p>If we study the legitimate values of the first row cells, as these are generated by our cacheValidValues() function, we make the observation that some numbers appear as legitimate values for many cells, and some other numbers for fewer cells. Since we already know that each number from 1–9 should definitely make their appearance in each row, it is evident that these numbers appearing less frequently will have greater probabilities to prevail in a cell rather than the ones who are eligible for half or even more cells of the row.</p><p>To make this more clear with a visual example:</p><p>For the first row of the given board, we have extracted the legitimate values for each cell and added them within brackets. Collecting the values from all cells of row 1 we notice that number 6 appears as a candidate value only in 2 cells, while numbers 1,5,7,9 appear in 4 different cells.</p><p>This is translated to number 6 having better chances of prevailing in a certain cell when it is competing against numbers with higher frequencies (based on the information extracted by the row alone).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*u9g-oXXVEQPxoyDF_MGjkg.jpeg" /></figure><p>The way to take advantage of the information is by ordering the lists of legitimate values for each cell (which already have been made available in our cache) by chance of prevelance, thus the numbers with lower frequency of appearance in the row cells will be more likely to be the correct options eventually and we will make it so that they will presented first in our algorithm when iterates through the legitimate values.</p><p>To achieve this, we create a new function to go through the frequency of appearance for each row and will return a cache with ordered list of legitimate values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2ca95bdcab430342bdb32ee650ead29/href">https://medium.com/media/d2ca95bdcab430342bdb32ee650ead29/href</a></iframe><p>After the latest modification, we give our program a try and write down the execution time for our program :</p><blockquote>The execution time of above program is : 13.673209190368652 s</blockquote><p>This is an improvement compared to our previous implementation of the unordered cache, but we will try to take it a step further:<br>So far we have created a data structure where we save the potential values for each cell and we ordered them based on how many times this candidate value appears on cells of the same row-the less frequently appears the more priority we give this value during our backtracking iteration.</p><p>Next idea is to integrate in our algorithm as well information coming from the cell’s column and block. As depicted in the following visual, for the cell [0][1] we have the legitimate values [1,4,5,7,9].<br>Based on the appearance frequency analysis for all the cells related to the one we are interested in, we can order the list of legitimate values as following : [4,7,1,5,9] which we hope will limit the wrong guesses and consequently iterations of our backtracking algorithm.</p><figure><img alt="Full by hand frequency appearance analysis for cell [0][1]" src="https://cdn-images-1.medium.com/max/620/1*bGEqAcgBsAtdckrrhBPUoA.jpeg" /><figcaption>Full by hand frequency appearance analysis for cell [0][1]</figcaption></figure><p>We then need to create a new lengthy function in order to implement the logic described above. Now we do not iterate only through the cells of a row to collect the frequency of appearance, but also through the cells of each column and each block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3487494574e46a0efc70a3c090402b7/href">https://medium.com/media/a3487494574e46a0efc70a3c090402b7/href</a></iframe><p>As soon as our new code is free of bugs, we give it a try to measure performance:</p><blockquote>The execution time of above program is : 13.849200248718262 s</blockquote><p>We notice that this new logic did not improve our program as we would have expected. Information from rows, columns and blocks combined did not help our algorithm to guess more efficiently.<br>There is still room for significant improvement however, as we see in <a href="https://medium.com/@ev.zafeiratos/sudoku-solver-with-python-a-methodical-approach-for-algorithm-optimization-part-3-9bfc1d9f38fc">Part III</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c48e83b89d20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sudoku Solver with Python : a methodical approach for algorithm optimization[part 3]]]></title>
            <link>https://medium.com/@ev.zafeiratos/sudoku-solver-with-python-a-methodical-approach-for-algorithm-optimization-part-3-9bfc1d9f38fc?source=rss-bd0ceda7f600------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bfc1d9f38fc</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sudoku]]></category>
            <category><![CDATA[optimization-algorithms]]></category>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Evangelos Zafeiratos]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 13:43:35 GMT</pubDate>
            <atom:updated>2022-02-16T16:07:35.599Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/b2c99887167f?source=post_stats_page----------------------------------------">Sudoku Solver with Python : a methodical approach for algorithm optimization[part 3]</a></h3><p>This is the third and final of a series of articles dedicated to the popular game of Sudoku. More particularly, how we can build a script to automatically solve Sudoku puzzles with recursion and consequently improve its performance.</p><p>In this final article we will be showing the final additions to our algorithm to complete the transition from a fully recursive solution into a hybrid solution which enables recursion only when we cannot derive new values from the information already provided on the board.</p><figure><img alt="Sudoku Solution via iterations" src="https://cdn-images-1.medium.com/max/620/1*SH5SAvVp9zdypWL0OVHZpw.gif" /><figcaption>Sudoku solution via iterative method</figcaption></figure><h3>Take full advantage of board Info</h3><p>In Part II we focused on creating a cache which will store the legitimate values for each cell and even prioritize their feeding into the backtracking algorithm based on how low the frequency of their appearance for all the competitive cells is.</p><p>We deliberately ignored one very important attribute, the one that every person that has solved a Sudoku puzzle in their life are using to progress on the actual task of solving the Sudoku: it can occur that for a given block, row or column there is only one single cell for which a certain value is allowed. When this happens, we can simply advance by setting this value in our board.</p><p>This attribute is portrayed in the following table : after analyzing the legitimate values for each empty cell of the 1st block, we make the observation that 4 appears only in the list of values for cell [0][1]. Therefore we can instantly set the value of cell [0][1] to 4 and save costly operations from our algorithm.</p><figure><img alt="Making use of block information to add new value" src="https://cdn-images-1.medium.com/max/620/1*pYILXp24Ko7ewrOX7qz7JA.gif" /><figcaption>Making use of block information to add new value</figcaption></figure><p>The same applies for columns and rows so the purpose is to integrate in our orderedValidValues() function the logic for adding a value to the board already :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fe9dedc5e485b7ac74921d8c8ec36a4/href">https://medium.com/media/4fe9dedc5e485b7ac74921d8c8ec36a4/href</a></iframe><p>We get the following results for our new colde:</p><blockquote>The execution time of above program is : 3.7023189067840576 s</blockquote><p>This is already a significant performance improvement since it shortens the depth in which the backtracking algorithm would need to search for the correct value. <br>There is one final tweak in our program to conclude the analysis.</p><h3>Hybrid Solution : Board Scanning and Recursion</h3><p>The previous solution enhances the performance by giving a better head start to the recursive algorithm : it scans the board once and it tracks cells for which we can set values already. Then it sends the ordered cache to the backtracking algorithm to continue the task.</p><p>This is how the beginning of such an execution by hand would look like:</p><figure><img alt="Hybrid Sudoku Solution with 1 scanning" src="https://cdn-images-1.medium.com/max/620/1*MkR-kkxHamY7nhuaciUjUw.gif" /><figcaption>Hybrid Sudoku Solution with 1 scanning</figcaption></figure><p>The next idea is whether it is possible to minimize as much as possible the use of our backtracking algorithm. We know that scanning the board once would give us some new values already. Exactly thanks to these values our algorithm could reevaluate the board state and potentially give us new values in the next scanning.</p><p>Let’s see what happens when we scan the board for the second time :</p><figure><img alt="Making use of block information to add new value" src="https://cdn-images-1.medium.com/max/620/1*StxQS3r0JvViJBAKYRJSfw.gif" /><figcaption>Block new Values after 2 scannings</figcaption></figure><p>Second scanning has added some new values to our board. This is definitely encouraging and directs us to the final tweak in our algorithm which is concluded by the instruction:<br><strong>Scan the board as many times as new values are being added and only when no values are added, give control to backtracking algorithm.</strong></p><p>This is implemented with the following flag that as long as it is True, our program will run the scanning and setting values for new cells.<br>The moment we cannot find new values by this method is when backtracking is enabled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/259e8027224578541c877c2834c84f7f/href">https://medium.com/media/259e8027224578541c877c2834c84f7f/href</a></iframe><p>Now let’s make a by-hand execution of our example Sudoku board to see what actually occurs.</p><figure><img alt="Sudoku solution via iterative scannings" src="https://cdn-images-1.medium.com/max/620/1*SH5SAvVp9zdypWL0OVHZpw.gif" /><figcaption>Sudoku solution via iterative scannings</figcaption></figure><p>We can see that few iterations of our scanning function are sufficient to solve the puzzle, our program did not need to go through the backtracking algorithm.<br>Nevertheless, we expect that there will be also Sudoku puzzles where progress of the scanning function will be halted after some iterations and afterwards backtracking should be available as the Plan B option.</p><p>Finally let’s see how our program handles with the 50-Sudoku benchmark that we have been using through this series of articles :</p><blockquote>The execution time of above program is : 0.7639837265014648 s</blockquote><p>As expected this is the fastest of all previous solutions, and this will be the closure for this analysis, purpose of which was not to build the most optimal Sudoku solver out there, but rather demonstrate the incremental optimization by adding more sophisticated logic to our algorithm.</p><p>If you missed the Part I of the series you can <a href="https://medium.com/@ev.zafeiratos/sudoku-solver-with-python-a-methodical-approach-for-algorithm-optimization-part-1-b2c99887167f">read it here</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bfc1d9f38fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sudoku Solver with Python : a methodical approach for algorithm optimization[part 1]]]></title>
            <link>https://medium.com/@ev.zafeiratos/sudoku-solver-with-python-a-methodical-approach-for-algorithm-optimization-part-1-b2c99887167f?source=rss-bd0ceda7f600------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2c99887167f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sudoku]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sudoku-solver]]></category>
            <dc:creator><![CDATA[Evangelos Zafeiratos]]></dc:creator>
            <pubDate>Mon, 07 Feb 2022 21:16:53 GMT</pubDate>
            <atom:updated>2022-02-16T13:46:29.763Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sudoku Solver with Python : a methodical approach for algorithm optimization [part 1]</h3><p>This is the first of a series of articles dedicated to the popular game of Sudoku. More particularly, how we can build a script to automatically solve Sudoku puzzles with recursion and consequently improve its performance.</p><p>This first article focuses on displaying the backtracking algorithm which is utilized to build the Sudoku solver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DZ0d86IyXaiiWdmW" /><figcaption>Photo by <a href="https://unsplash.com/@maplerockdesign?utm_source=medium&amp;utm_medium=referral">Richard Bell</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Origin of the name comes from the Japanese phrase “<em>suuji wa dokushin ni kagiru”, which means “the numbers (or digits) must remain single.”</em></blockquote><p>Popularity of the particular puzzle of numbers derives from the simpicity of its rules as well : Sudoku is played on a grid of 9 x 9 spaces. Within the rows and columns are 9 “squares” (made up of 3 x 3 spaces). Each row, column and square (9 spaces each) needs to be filled out with the numbers 1–9, without repeating any numbers within the row, column or square.</p><p>The focus of the following series of articles is to display the steps of :<br>1. building a Python program to automatically solve Sudoku puzzles<br>2. incrementally implementing performance optimizations to our code<br>3. measuring performance using a 50-Sudoku file as our benchmark</p><h3>Setting up our board</h3><p>This very step initializes our board with a set of numbers as these are provided by the problem. A function named <em>setBoard()</em> is converting the input into a suitable data type for our consequent operations. Following conventions are made:</p><ul><li>Empty cells are initialized with a ‘0’ value.</li><li>The data type for maintaining the digit values of the Sudoku puzzle is a 2-dimensional list of 9x9 size.</li></ul><p>Of course our code for populating our 2-D list is adjusted on the input, which in this case is a multi-line string. After the function completes all operations it returns the list named ‘<strong>board</strong>’ including all input values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72d4aea144f460db0cfeac1852d5f88e/href">https://medium.com/media/72d4aea144f460db0cfeac1852d5f88e/href</a></iframe><p>And this is how our puzzle would look in a nice visual environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*WkAsULnJPWnunz6hOuAJ-A.jpeg" /><figcaption>Initial Sudoku board</figcaption></figure><h3>Finding next empty cell</h3><p>Operation of the <em>findEmpty()</em> function is fairly simple : a reference to the board is passed as parameter and then the function traverses the board until it finds the first empty cell which is returned.<br>In case it finds no empty cells this is an indication that our problem is solved, so it returns ‘<em>None</em>’ value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f72077d39f58323602cf4bf41247b06/href">https://medium.com/media/6f72077d39f58323602cf4bf41247b06/href</a></iframe><h3>Check value validity in cell</h3><p>The operation <em>isValid()</em> function performs is to confirm whether a given number is a valid option for a particular board cell. There are 3 requirements that should be met in order for the value to be accepted into the board :</p><ol><li>None of the cells of the same row should contain the examined number</li><li>None of the cells of the same column should contain the examined number</li><li>None of the block cells should contain the examined number</li></ol><p>If all of the above is met, function returns <em>True</em> which will trigger the insertion of the new value into our board.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f40f87de87aa1e67a7a665321cf5bfc5/href">https://medium.com/media/f40f87de87aa1e67a7a665321cf5bfc5/href</a></iframe><p>Herewith is an example of a successful insertion of a new value after passing the conditions described in <em>isValid()</em> function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*0SqCqHfzw2satsZsa88jnA.gif" /><figcaption>isValid() function : success</figcaption></figure><p>On the contrary, when we introduce a value which conflicts with one of the already established values on the board, this will be rejected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*Q9FvuJGdpdCCItrQy99JDg.gif" /><figcaption>isValid() function : fail</figcaption></figure><h3>Implement backtracking algorithm</h3><p>The next function is the main core of our solution, where backtracking is introduced : the algorithm can be described by the following steps:</p><ol><li>Search for the next empty cell. If none is found, then we have already solved the puzzle, if not move to step 2.</li><li>Make a guess on the correct number by iterating numbers 1–9 and simply examine whether it is a valid solution, given the already established numbers in the board.</li><li>If a valid number is found, call the <em>solve()</em> function recursively and make a guess for the next empty cell.</li><li>If none of numbers 1–9 is valid, previous call of the function will reset the value of the cell to 0 and continue iterating to find the next valid number.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96e07d2a7714741786eaa183738ebfc1/href">https://medium.com/media/96e07d2a7714741786eaa183738ebfc1/href</a></iframe><p>Since recursion is not the most intuitive conception, let’s try to vizualize by an example of solving by hand our Sudoku puzzle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*j8MPSdY8HnPGoe8vIlbOCw.gif" /><figcaption>Backtracking Algorithm by hand</figcaption></figure><p>As you can see in the example above, the algorithm fills the empty cells with valid numbers until there is a deadend. Then it backtracks (in this case 3 entire cells) until the process is re-iterated.</p><h3>Performance</h3><p>Our program needs to iterate through many potential values for each cell with the backtracking algorithm . This is non-optimal of course and we expect a slow performance for our solution.</p><p>Indeed, after using the benchmark of 50-Sudoku puzzles as provided by <a href="https://projecteuler.net/problem=96">Project Euler (Problem 96) </a>the execution time is :</p><blockquote>The execution time of above program is : 23.56185507774353 s</blockquote><p>You can read how we add some intelligence to our program in the <a href="https://medium.com/@ev.zafeiratos/sudoku-solver-with-python-a-methodical-approach-for-algorithm-optimization-part-2-c48e83b89d20">next article of the Series</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2c99887167f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Analysis on NBA comeback victories]]></title>
            <link>https://medium.com/@ev.zafeiratos/data-analysis-on-nba-comeback-victories-4721b5a54224?source=rss-bd0ceda7f600------2</link>
            <guid isPermaLink="false">https://medium.com/p/4721b5a54224</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[visme]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Evangelos Zafeiratos]]></dc:creator>
            <pubDate>Mon, 31 Jan 2022 23:04:02 GMT</pubDate>
            <atom:updated>2022-02-01T17:29:28.646Z</atom:updated>
            <content:encoded><![CDATA[<p>Data Analysis Framework with complete ETL using Python for Web Scraping, Pandas for transforming and loading data and finally Visme to visualize key insights.</p><figure><img alt="NBA Full Court View" src="https://cdn-images-1.medium.com/max/1024/0*sqVocD21Zqr9gVGn" /><figcaption>Photo by <a href="https://unsplash.com/@_miltiadis_?utm_source=medium&amp;utm_medium=referral">Miltiadis Fragkidis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the few sport events I follow is NBA league and besides enjoying the game of basketball I very often find myself digging into stats of players or teams.<br>Last week on January 25 there was an astonishing event, of the ones called outliers in the statisticians world : the Los Angeles Clippers pulled off an amazing comeback from -35 points to win the game against the Washington Wizards. <br>As amazing this result truly were, my gut feeling from watching the game for many years was that comeback victories is not such a rare occasion as it used to be in the past. I decided to run a detailed analysis to put my theory under the infallible microscope of exploratory analysis.</p><h3>Gathering the Data</h3><p>In order to get the data I need for the analysis, I had to go to the source. <a href="https://www.basketball-reference.com/">https://www.basketball-reference.com/</a> is a website which hosts tons of data when it comes to sports events including Play-by-Play information from every single NBA game since season 1996–1997.</p><p>Next step was to create a script to pull all this data for further analysis. After examining carefully the website sitemap i created a Python function which builds a list of all Game URLs for a single season:</p><pre>def extractGameURLs(year):<br> URLs_list = list()<br> domain_URL = “<a href="https://www.basketball-reference.com/leagues/NBA_">https://www.basketball-reference.com/leagues/NBA_</a>&quot;<br> year_URL = domain_URL + str(year) + “_games-”<br> months = [‘october’, ‘november’, ‘december’, ‘january’, ‘february’, ‘march’, ‘april’, ‘may’, ‘june’ ,’july’]<br> for month in months:<br> URL = year_URL + month + “.html”<br> page = requests.get(URL)<br> soup = BeautifulSoup(page.content, “html.parser”)<br> schedule_div = soup.find(id=”schedule”)<br> schedule_str = str(schedule_div)<br> # We are looking to match the string “201410280SAS” that is used in creating the NBA boxscores URL<br> regex = ‘\d{9}\w{3}’<br> match = re.findall(regex,schedule_str)<br> for item in (set(match)):<br> URLs_list.append(item)<br> URLs_list.sort()<br> return URLs_list</pre><p>Next, BeautifulSoup &amp; Python libraries would need to take over in order to convert all this HTML into a structured data table. I won’t get into the tiniest detail of the implementation, I will just present you the main function that handles the URL provided by the previous extractGameURLs() function and utilizes more functions for each specific analysis.<br>[ You can find the full Source code in the corresponding <a href="https://github.com/evangelos-zafeiratos/NBADataAnalysis">Github repository</a> ]</p><pre>def pbpRead(pbp_URL):<br>    httpString = &#39;<a href="https://www.basketball-reference.com/boxscores/pbp/&#39;">https://www.basketball reference.com/boxscores/pbp/&#39;</a><br>    finalURL = httpString + pbp_URL + &#39;.html&#39;<br>    page = requests.get(finalURL)<br>    soup = BeautifulSoup(page.content,&quot;html.parser&quot;)<br>    a = soup.find_all(re.compile(&quot;game_summaries&quot;))<br>    URL = finalURL[-31:]<br>    homeTeam, awayTeam = teamNames(soup)<br>    gameType = gameTypeDecider(soup)<br>    date, time, location = locationGameTime(soup)<br>    winningTeam = findWinner(soup,homeTeam, awayTeam)<br>    fixedList = [URL,gameType,location,date,time,winningTeam,awayTeam,homeTeam]<br>    playByPlay(soup,fixedList)</pre><p>Last, but not least, a for loop automates the script and calls each of the previously mentioned functions including a writeCsvHeader(fileName) function, which has the mission of printing all the gameplays for an entire season on seperate CSV files.</p><p>After the script running successfully (I didn’t bother for any code optimization and the volume of data was quite large, so it took roughly a day) we have the following files made available in our directory :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*bxWDymCHzrZSII2NfsZIdw.png" /><figcaption>Pbp NBA data since 1996–1997 Season</figcaption></figure><h3>Transforming the Data</h3><p>My main area of interest on the play-by-play dataset of NBA games is the comeback victories so the data needs to be transformed accordingly. <br>I utilized of course the powerful Pandas library to achieve this.</p><p>Rather than going into the details of the Pandas Source code (which you can also find in the Project Repository) I will explain the thinking behind my analysis in which i opted for the following 3 metrics :</p><ul><li>Ratio of Comeback victories from 10+ points</li><li>Ratio of Comeback victories from 20+ points</li><li>Average points on Comeback victories</li></ul><blockquote>[ Ratio is the number of games that meet the requirement divided by the number of season games and it consists of a more safe metric than absolut number of games due to seasons with less games either due to lockout or Covid ].</blockquote><p>I decided to extend the metric above to detect comeback victories from a large deficit on 4th quarter, because covering a point disadvantage of 20+ points that occurs during 1st or 2nd Quarter is a great athletic feat, but when a team achieves this during the 4th Quarter with less than 12&#39; remaining in the game clock, this is extraordinary.</p><p>On top of the metrics, I wanted to extract the record comeback from each season as this is an interesting insight.</p><p>My final version of data which I use for the visualization is 2 dataframes (one for each set of metrics) which are initiated in this piece of code :</p><pre>NbaData = { &#39;Comeback 10Points+&#39; : plus10PointsRatio, &#39;Comeback 20Points+&#39; : plus20PointsRatio, &#39;Average Comeback&#39; : avgComeback, &#39;YearRecord&#39; : yearlyComeback}<br>    if quarter == 4 :<br>        NbaSeasonQ4Df = pd.DataFrame(data = NbaData, index = seasonList)<br>        return NbaSeasonQ4Df<br>    else:<br>        NbaSeasonDf = pd.DataFrame(data = NbaData, index = seasonList)<br>        return NbaSeasonDf</pre><p>..and they look something like this :</p><figure><img alt="Dataframe from NBA Comeback Victories metrics" src="https://cdn-images-1.medium.com/max/962/1*SoOLxe42zvLJJgXTi-NMfg.png" /><figcaption>Dataframe with NBA Comeback Victories Data</figcaption></figure><h3>Loading &amp; Visualizing Data</h3><p>Moving to the part that is more interesting to the NBA fans and stat lovers, displaying our findings! <br>I decided to use the free version of Visme for visualizing my data. This is a tool with limited data manipulation options, but I chose it because of the design aesthetics and moreover since my dataset is not dynamic, I saw this as an one-off analysis:</p><p><em>Visualization 1 :</em></p><p>It is confirmed that comeback victories are more common these days, as shown in the first viz : not only we can see the trend increases, but there is also a significant increase on the ratio of 10+ points comeback victories since season 2016–2017 when it was the first time the ratio surpassed 25% meaning 1/4 teams trailing for 10 or more during the game would end up winning!</p><figure><img alt="10+ Points Comeback Victories Ratio" src="https://cdn-images-1.medium.com/max/1024/1*-TuO6_wr1U1JQ43uxZllXA.jpeg" /><figcaption>10+ Points Comeback Victories Ratio</figcaption></figure><p><em>Visualization 2 :</em></p><p>The metric of 20+ points comeback victories tells no different story : we have 3 consecutive seasons during 2017–2020 where the ratio surpasses 2% for the first time. In absolute terms, the number of games where 20+ points comeback victories occured for these seasons where 3 and 4 times the number of games in seasons during late 90’s and early 00’s .</p><figure><img alt="20+ Points Comeback Victories Ratio" src="https://cdn-images-1.medium.com/max/1024/1*WZtL4QjwDsOWQPbKWTuoew.jpeg" /><figcaption>20+ Points Comeback Victories Ratio</figcaption></figure><p><em>Visualization 3 :</em></p><p>10+ points comeback victories on 4th quarter confirm the trend. From having multiple seasons around 3% ratio in the past, during the last few seasons this percentage is well above 4% (never surpassed the 5% threshold though) .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3C2a8vN11YAUvkhZBa_Lg.jpeg" /></figure><p><em>Visualization 4 :</em></p><p>The following is a tribute to the teams that achieved the almost impossible. A summary of the greatest comeback victories per NBA Season since 96–97.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FFuojO8RY4OfU1qzf2ZNpw.jpeg" /><figcaption>Greatest comebacks by NBA Season</figcaption></figure><p><em>Visualization 5 :</em></p><p>Finally, the overview of greatest 4th Quarter comeback victories per Season. Some of the entries in this table are simply amazing, with the <br>Dallas Mavericks 103 @ <strong>Los Angeles Lakers 105 </strong>game being the most outstanding. The team from L.A. wrote history when on December 6, 2002 they were down by 27 on 4th quarter and astonishingly came back to win the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whfQygopFidRJh4x13IMiw.jpeg" /></figure><p>More insights on NBA games soon.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4721b5a54224" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power Bi Dashboard using web scraping with Python]]></title>
            <link>https://medium.com/@ev.zafeiratos/power-bi-dashboard-using-web-scraping-with-python-94d9ba92f5b7?source=rss-bd0ceda7f600------2</link>
            <guid isPermaLink="false">https://medium.com/p/94d9ba92f5b7</guid>
            <category><![CDATA[macroeconomics]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Evangelos Zafeiratos]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 16:25:59 GMT</pubDate>
            <atom:updated>2022-02-02T12:29:05.011Z</atom:updated>
            <content:encoded><![CDATA[<p>Combine multiple data sources to build a meaningful dashboard</p><figure><img alt="Power Bi Dashboard displaying Greece macro economy KPIs" src="https://cdn-images-1.medium.com/max/1024/1*L0T96yF6DFsAE_jaOK4xpw.gif" /><figcaption>Interactive Power Bi dashboard</figcaption></figure><p>Information and data is consumed at an enormous pace in our modern society, whereas at the same time the human attention span has markedly decreased also due to the bombardment of stimulation from multiple sources.</p><p>Data Visualization is powerful with its intrinsic ability to offer condensed pieces of information in a manner which is friendly to the human brain, thus it is gaining more and more popularity. Moreover, economy and finance has traditionally been one of the domains where data visualization is heavily used and today this is no exception.</p><p>The facts above generated the idea for this project which is to combine several macro and price indices of Greece economy into a single dashboard. Logic behind the selection of the specific metrics is to provide a glimpse into Greece economy that would be meaningful for the average person (the dashboard is by no means suited for investors as it doesn’t deep-dive into the details) .<br>Purpose of this article is to describe the methodology and share some insights on the challenges I faced that might be useful to the ones working on similar projects.</p><h3>Phase 1 : The Research</h3><p>As already mentioned, metrics for the dashboard were selected having the average person in mind : what would someone living in Greece need to know about their country’s economy deriving from the indices? I concluded to the following 4 pillars :</p><ol><li><strong>Stock Market Index<br></strong>In every modern country the stock market is a vital part of the economic ecosystem and is as well frequently used as an indicator of the country’s performance. I decided to use the Athens Stock Marcket (ΧΑΑ) index value but to skip all the individual indices.</li><li><strong>Basic Macro-economic Metrics<br></strong>A proper analysis of a country’s economic outlook would involve dozens, if not hundreds of KPIs, metrics and indices. I have included just a bunch of them, the ones I consider as the most impactful in people’s everyday lives:<br>- GDP growth : the annual rate in which the economy grows<br>- Unemployment : the % of economic active population who are jobless<br>- inflation : the rate of rising prices of goods and services</li><li><strong>Bonds <br></strong>A common practice for raising money either by countries or corporations in today’s economy is by issuing bonds. The yield by which the country borrows money is a very reliable indicator of the country’s credibility to the money markets. For Greece with her recent economic turmoil, these indicators are even more important.<br>I have added the long term bonds that the country has issued over the last years, both 10Year and 20Year bond.</li><li><strong>Energy Price<br></strong>Out of the multiple price indices, those concerning energy have the most significant impact in economic activity and purchasing power of the population consequently. I chose to include graphs showing the price variation of the most commonly used energy sources : diesel &amp; unleaded representing fuel and electricity as the main household energy source.</li></ol><h3>Phase 2 : Finding Sources</h3><p>Finding an API to retrieve all of the data mentioned above proved to be a non-option as all the relevant APIs were either insufficient or too costly. Next available option was to use web scraping to retrieve this data from existing websites. This option has the following risks:<br>a) Websites collecting data (especially the ones offering the option of paid API to get access to their data) could potentially enable a strict policy against scraping, which would break the gateway to our dashboard.<br>b) Web scraping techniques are based on the exact structure of the website at the given moment to access the necessary data, therefore any slight change in the HTML or CSS code (i.e changing the class name of a table) might break our code as well.<br>However, for a non-production project this is an acceptable risk. Plus, I looked for relatively stable websites as my data sources. The ones I selected :</p><p><a href="https://tradingeconomics.com/">Trading Economics</a> : Used to retrieve all macro economic indices, bonds &amp; stock market index.<br><a href="https://statista.com/">Statista</a> : Data source for monthly electricity price<br><a href="https://gr.fuelo.net/">fuelo.net</a> : Data source for average fuel price (diesel &amp; unleaded)</p><h3>Phase 3 : Writing some Python Code</h3><p>I used Python and the powerful BeautifulSoup library to parse the HTML from the source websites. Since Power Bi does only recognize Pandas DataFrame data structure as potential input, I had to make a conversion to DataFrame for each individual table.<br>I divided my code into 4 separate functions (one for each data retrieval process) and after ensuring it retrieves the data in the correct format I used this code as my data source in Power Bi (which I will describe in Phase 4). <br>You can see through the schematic below the steps beginning with our integrated Python script and ending in the final data model we will use for the Dashboard. In a nutshell:<br>1. HTML Retrieval<br>2. HTML parsing and conversion to DataFrames<br>3. Power Query conversion of DataFrames to data tables</p><p>I will not dive into more details on the python script, you can have a look at the source code residing in this <a href="https://github.com/evangelos-zafeiratos/DataVisualization">repository</a>.</p><figure><img alt="Dataflow" src="https://cdn-images-1.medium.com/max/800/1*Fyfxo4qWFbNwspfa4sTZHw.jpeg" /><figcaption>Project dataflow structure</figcaption></figure><h3>Phase 4 : Power Bi Configuration &amp; Presenting Data</h3><p>Power Bi offers countless ways of importing data to your model, one of which is through a Python Script.</p><figure><img alt="Screenshot from Power Bi Get data menu" src="https://cdn-images-1.medium.com/max/595/1*cNppuWeNVetYQc-d0lXfrQ.png" /><figcaption>Screenshot from Power Bi Get data menu</figcaption></figure><p>Power Query will run the script, retrieve the data and store them in separate tables. Our next consideration would be to confirm that the data types Power Query has presumed are the appropriate ones, and make changes if applicable.</p><p>Once our data model looks like in the screenshot below we are ready to jump into the visualization process!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*Ubdl0TQjIYWPblcXlsGqzQ.png" /></figure><p>The visualization is rather simple and I used only 3 types of visuals to achieve : Cards, a custom Scroller &amp; Line Charts.</p><p>Cards are used to diplay all macro values (GDP growth, unemployment, inflation) and bonds price and variation.<br>A scroller is utilized to display the stock index whereas line charts are adding some interactivity to the dashboard, as they display a whole set of values which can be previewed once the user hovers the mouse over the graphic.<br>Finally, a slicer linked with the line charts only can be used to extend or shorten the time span of the fuel price observation.</p><p>You can see the final version of the dashboard in the link below:</p><p><a href="https://app.powerbi.com/view?r=eyJrIjoiNjA1YTUwNmYtOTA5Ni00ZTc3LWE2ZTgtMmMwNWYzYmEzZGQ1IiwidCI6IjI1ZTU3ZWQxLTJhZWMtNGVhOC04YzUyLWYwODA3MjM5MTlhZSIsImMiOjl9&amp;pageName=ReportSection">Power BI Report</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94d9ba92f5b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is European Green Deal feasible?]]></title>
            <link>https://medium.com/@ev.zafeiratos/is-european-green-deal-feasible-8e996ad7f596?source=rss-bd0ceda7f600------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e996ad7f596</guid>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[energy]]></category>
            <category><![CDATA[european-green-deal]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[renewable-energy]]></category>
            <dc:creator><![CDATA[Evangelos Zafeiratos]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 03:50:10 GMT</pubDate>
            <atom:updated>2022-01-19T13:33:44.123Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A reality check on the new ambitious plan by the European Union to increase target for renewable energy sources share of total energy consumption by 2030.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DeUBBKgIWhjK86nK" /><figcaption>Photo by <a href="https://unsplash.com/@zburival?utm_source=medium&amp;utm_medium=referral">Zbynek Burival</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Amidst the discussion on climate change and global warming concerns, the European Union announced on July a new ambitious plan to raise the share of renewable energy to 40% on total energy consumption by 2030. This decision came only 3 years after the previous agreemenent that at least 32% of the Union’s gross energy consumption in 2030 would originate from renewable sources.</p><p>Purpose of this article is to dive into the underlying data as provided by Eurostat (<a href="https://ec.europa.eu/eurostat/databrowser/view/NRG_BAL_C/default/table?lang=en&amp;category=nrg.nrg_quant.nrg_quanta.nrg_bal">energy balances dataset</a>) and perform an analysis on the energy profile not only of EU-27 countries, but of the extended dataset of 42 European countries over the course of the last 3 decades, hence since 1990 when detailed energy data started to be recorded.<br>While dealing with the actual data during the analysis, few surprisings insights emerged which pushed my research even further in order to better comprehend the causes and share in this article.</p><h3>Interactive Power Bi dashboards</h3><p>Before proceeding to the rest of the article, it is highly suggested to access the available Power Bi report by clicking on the link below.</p><p><a href="https://app.powerbi.com/view?r=eyJrIjoiYmRhMjM0YTYtZDQ0YS00MGU5LWFiMjMtZDdlYWVkMDBmOWRlIiwidCI6IjI1ZTU3ZWQxLTJhZWMtNGVhOC04YzUyLWYwODA3MjM5MTlhZSIsImMiOjl9&amp;pageName=ReportSection0aa25744cffea64981fe">Power BI Report</a></p><h3>Energy Sources</h3><p>The following table cites the 6 major categories of energy sources including their subcategories. This very frequently used categorization in bibliography, which can be met in Eurostat articles, is also used in the present analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*MbNwdLX5psT0FWn1gI1zpQ.png" /></figure><h3>Green energy champions</h3><p>With the focus given on Renewable energy, the following graphic depicts the energy share by source and we can easily derive from the top rows the renewable energy ‘champions’ .</p><p>By large margin Iceland is leading all European countries in the rankings for the most clean energy comsumer, as the country recorded an impressive 87.8% of the total energy consumption coming from renewable sources during the year 2020. Vast majority of this is coming from hydropower and also geothermal which is offered plentifully in the country’s volcanic landscape.<br>The country’s energy profile is the perfect success story, as the country was heavily relying on fossil fuels back in 1970 (<a href="https://ourworldindata.org/energy/country/iceland">source</a>) and they managed a radical transformation until this day, where it is almost fully relying on renewable energy sources.</p><p>On top of the list unsurprisingly Scandinavian countries make their appearance. While for Sweden and Norway geography plays a vital role, as they have largely invested in hydropower thanks to the moving waters surrounding the countries, Finland is a case of its own : biofuels are the main source of renewable energy followed by hydropower by a wide margin and minor contributions by solar and wind energy (<a href="https://www.iea.org/countries/finland">source</a>). Finland’s nuclear plants further improves the country’s clean energy profile.<br>Renewable energy mix for Denmark is also based on biofuels, whereas wind &amp; solar also contribute a smaller part and hydro is only a minor energy contributor (<a href="https://www.iea.org/countries/denmark">source</a>).</p><p>A surprising entry in the list of green champions comes from the country of Latvia : renewable energy share stands for a respectable 39.6% of the country’s overall consumption. Biofuels contribute the lion’s share, whereas the country’s large network of rivers and lakes enables the production of hydropower as well.</p><p>Albania’s ranking 5th for year 2020 should come by no surprise as the country’s investment in hydropower originates at least since 1990 resulting in the country ranking steadily in top 5 positions of the corresponding category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNKUXhdkx7Ecpfqn2ZiInA.jpeg" /><figcaption>Graphic 1</figcaption></figure><h3>Europe Energy map</h3><p>The following graphic intends to summarize the previous findings, and by dividing the share of renewables energy into discrete bins to provide an opportunity to the reader for a quick insight and comparison between the countries.</p><p>The only countries in the top tier (&gt;50%) are Iceland and Norway with all the rest following. It is worth noted that 6 countries find themselves residing on the bottom tier (&lt;10%) for year 2020, however this shows significant progress compared to 10 years ago where we can find 16 countries on the bottom tier, and especially compared to year 1990 where 25 countries recorded shares lower than 10% (14 of which even lower than 2%) .</p><p>One additional insight concerning the topic of this article is that 3 EU countries (Iceland, Norway and Sweden) already meet the target of 40% described by the European Green Deal.</p><figure><img alt="European map according to renewable energy share" src="https://cdn-images-1.medium.com/max/1024/1*R0CFwNfR9pj1u4R9KVFf1Q.png" /><figcaption>Graphic 2</figcaption></figure><h3>EU Target for 2030</h3><p>The ambitious target set by the European Commission implies that the current share of renewable energy should be doubled within the next 10 years. From a statistical perspective, a regression analysis shows that the green line will not extend to the target of 40% by 2030, however reality is far more complex than that. <br>Recent developments in solar power technology and also findings suggesting that the cost of renewable energy forms is significantly declining (<a href="https://www.weforum.org/agenda/2021/07/renewables-cheapest-energy-source/">source</a>) leave room for hope that this aggressive target will motivate EU policymakers to embrace green energy in the following decade.</p><figure><img alt="EU average yearly shares for clean energy" src="https://cdn-images-1.medium.com/max/1024/1*n1WRFFe7dHX9CSmVm_ntqQ.jpeg" /><figcaption>Graphic 3</figcaption></figure><h3>End of era for solid fossil fuels</h3><p>Finally, an encouraging insight from the data analysis is the following graphic depicting the gradual and even rapidly accelerating the last few years decline of fossil fuels as an energy source for EU countries.<br>During the year 2020 solid fossil fuels accounted to only 10.3% of energy consumed by these countries signifying a 60% drop from the share the source recorded in 1990 (25%). <br>Experts suggest that this drop will continue due to the higher cost compared to alternative forms of energy, but also the environmental agreements for the reduction of carbon emissions unanimously pointing fossil fuels as the most polluting and dangerous energy source we use today.</p><figure><img alt="EU average yearly shares for dirty energy" src="https://cdn-images-1.medium.com/max/1024/1*phKejoTUEiD1-v0GiYiZmA.jpeg" /><figcaption>Graphic 4</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e996ad7f596" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find whether (0,0) lies inside a triangle or not (2-axis)]]></title>
            <link>https://medium.com/@ev.zafeiratos/check-whether-0-lies-inside-a-triangle-or-not-2-axis-57edd570e5b3?source=rss-bd0ceda7f600------2</link>
            <guid isPermaLink="false">https://medium.com/p/57edd570e5b3</guid>
            <category><![CDATA[geometry]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[topology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Evangelos Zafeiratos]]></dc:creator>
            <pubDate>Sat, 08 Jan 2022 20:26:21 GMT</pubDate>
            <atom:updated>2022-01-08T22:13:36.641Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*fRU7XGIZnY8rB8qnBV-W8g.jpeg" /></figure><p>The triggering for working on this particular problem has been Project Euler Problem 102 (for those of the readers interested in both topics of Programming and Maths and not familiar with Project Euler I highly recommend to take a look at <a href="https://projecteuler.net/">https://projecteuler.net/</a> ) where a dataset of 1000 trianges is given and the reader is asked to find out the number of triangles that contain the origin (0,0) on a Cartesian plane.</p><p><strong>Problem</strong></p><p>Given 3 points A,B,C find whether the triangle formed by these points contains the origin (0,0).</p><p><strong>Solution 1 (Mathematical approach)</strong></p><p>If we take any point and connect that point to each vertex of the triangle, the result is three subtriangles with areas A1, A2 and A3, as shown below. For a triangle with a total area of A, we call the subset (A1/A, A2/A, A3/A) the barycentric coordinates of point P.</p><p>To solve the problem, we will make use of the vector status of area, which means there is a direction associated with it. For each area, not only triangles, there is an entity defined as vector normal which is calculated by the cross product of the corresponding vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*nOWFwO0Bkl4Xbwf4c8W-VQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*tAsnhEzM107pr53TqrHWwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*5Xckw2okqd3YybxkGJmqSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*3TEVqpLdpcLsofxm0FysxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*u-xPt6mNDqLGpuLNorfu5Q.png" /></figure><p>Vector normals are vector measures as well, but since we operate on a<br>2–D plane the direction of these cross products is going to be z-axis itself.<br>We expect each of the subtriangle vector normals to have same direction with the direction of the original triangle vector normal.<br>Therefore, the condition to be met so that (0,0) resides within the triangle area is that each of the cross products calculated for sub-areas has the same sign as the cross product of the area A.</p><p>STEP 1 : Read each line from the file<br>STEP 2 : Initiate the vectors for main triangle &amp; subtriangles and calculate the vector normal for each.<br>STEP 3 : Check whether the condition described above is met and increase the corresponding counter if this is the case.</p><blockquote><em>OUTPUT:<br></em>The number of triangles containing point (0,0) is: 228</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*XvfzC8H1rLnz8ke5DM9D_Q.png" /></figure><p><strong>Solution 2 (Using existing Python library)</strong></p><p>Using the existing matplotlib.path library of Python we can verify whether our Mathematical approach is correct. Making use of the .Path &amp; .contains_point methods the solution is straight forward:<br>STEP 1 : Read each line from the file<br>STEP 2 : Describe each triangle shape using .Path method and passing as argument an np array with each triangle vertex.<br>STEP 3 : For each of these triangles test whether it contains (0,0) point by making use of .contains_point method and increase the corresponding counter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*i_F8e1zvRJaTHrncG52aeg.png" /></figure><blockquote><em>OUTPUT:<br></em>The number of triangles containing point (0,0) is: 228</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57edd570e5b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>