<?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 Naveen on Medium]]></title>
        <description><![CDATA[Stories by Naveen on Medium]]></description>
        <link>https://medium.com/@naveenkumarspa?source=rss-65beee3faf68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EFZMLAG3gXE8Bjfkumlh8A.jpeg</url>
            <title>Stories by Naveen on Medium</title>
            <link>https://medium.com/@naveenkumarspa?source=rss-65beee3faf68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:43:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@naveenkumarspa/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[Dynamic Programming for Brute-Forcers]]></title>
            <link>https://medium.com/hackernoon/dynamic-programming-for-brute-forcers-36f26c2466cf?source=rss-65beee3faf68------2</link>
            <guid isPermaLink="false">https://medium.com/p/36f26c2466cf</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[minimum-cost-problem]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[brute-forcers]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Wed, 01 Aug 2018 15:56:01 GMT</pubDate>
            <atom:updated>2019-05-08T06:36:48.630Z</atom:updated>
            <content:encoded><![CDATA[<p>There were huge number of sources on the <a href="https://hackernoon.com/tagged/internet">internet</a> on this topic but still we (me and my friend) couldn&#39;t understand any of it for a very long time until we fiddled with code and tracked the output for every change in the input. So this article is exactly created for people like us to make the transition from <a href="https://en.wikipedia.org/wiki/Greedy_algorithm">greedy</a> to dynamic <a href="https://hackernoon.com/tagged/programming">programming</a> easier. This will just be an introduction to dynamic programming, so that one can pick it up from there. I have added additional sources for practice and other online tutorials that I found a little helpful at the end. It is for programmers who are comfortable with brute-force and might not the serve the purpose for absolute beginners.</p><h3>Definition</h3><p>So what’s dynamic programming? Let’s first look at a more formal definition.</p><p>Dynamic programming (also known as dynamic optimization) is a method for solving a complex problem by breaking it down into a collection of simpler subproblems, solving each of those subproblems just once, and storing their solutions. The next time the same subproblem occurs, instead of recomputing its solution, one simply looks up the previously computed solution, thereby saving computation time at the expense of a (hopefully) modest expenditure in storage space. (Each of the subproblem solutions is indexed in some way, typically based on the values of its input parameters, so as to facilitate its lookup)<a href="https://en.wikipedia.org/wiki/Dynamic_programming">(Source-Wiki)</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89wcP4LUhvVPUJXpQ-vWeA.png" /><figcaption>It’s that simple</figcaption></figure><p>Or more simply, it is technique to save intermediate results in a calculation in any comfortable format so that the result can be used for further computation instead of calculating it all over again at the arrival of an additional input. Sounds simple enough? Yes, indeed it is, let’s have a look at an example to put it right through our skull.</p><p>Before that, we need to identify whether a problem has the following properties, inorder to be solved by Dynamic Programming(DP)</p><ol><li><a href="http://www.geeksforgeeks.org/dynamic-programming-set-1/">Overlapping Sub-problem</a></li><li><a href="http://www.geeksforgeeks.org/dynamic-programming-set-2-optimal-substructure-property/">Optimal Structure</a></li></ol><h3>Problems</h3><ol><li>Minimum Cost Problem</li><li>Longest Increasing Subsequence</li></ol><h3>Minimum Cost Problem</h3><p>Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. Total cost of a path to reach (m, n) is sum of all the costs on that path (including both source and destination). You can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1) and (i+1, j+1) can be traversed. You may assume that all costs are positive integers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*AvdW-76uv-nljCgTSFcDJw.png" /></figure><p><strong>Solution:</strong></p><p><strong>Me:</strong> So how would you go on solving that?<br><strong>Friend:</strong> Oh, the properties I read talked about saving the sub-problems to make the computations easier!<br><strong>Me:</strong> What are the sub-problems here? <br><strong>Friend:</strong> Oh, it’s too tough.<br><strong>Me:</strong> No, it’s not we will work together.</p><p>How would you normally solve it, forgetting about code for a minute.<br>You probably eye all the cells, adding the cost along the path till you reach the destination. But you don’t know if it’s minimum, so you start adding again by traversing in a different direction. Then maybe after considering all paths, you come up with a cost that’s give you the least.</p><p>That’s pretty much it.</p><p>My friend interrupts,<br><strong>Friend:</strong> But the above method only solves the problem for one particular destination, what if we want to calculate the total cost for reaching a different destination.<br><strong>Me:</strong> Good point!<br><strong>Friend:</strong> That’s why we store the minimum cost for reaching each cell in the array from the first cell. That way when we fill up all cells we will be left with solutions of every cell.<br><strong>Friend:</strong> I lost you there.<br><strong>Me:</strong> Haha, let me finish.</p><p>So what do we know so far?</p><ul><li>There’s an array and we can move right, down and digonally lower.</li><li>We need to print the minimum cost of traversing to the given destination.</li><li>And we start at the first cell.</li></ul><p><strong>Breaking down the problem:</strong></p><p><strong>Me:</strong> What is simply the cost of moving from [0,0] to [0,1]?<br><strong>Friend:</strong> It’s 2 + 1 = 3<br><strong>Me:</strong> What is the minimum cost of moving from [0,0] to [0,1]?<br><strong>Friend:</strong> Still 3, because there&#39;s no other way we could reach [0,1] since we can only move right or down or diagonally lower. We can <strong>only</strong> reach [0,1] from [0,0].<br><strong>Me:</strong> Excellent! So what is the minimum cost of moving from [0,1] to [0,2]?<br><strong>Friend:</strong> Oh wait, the cost of moving from <strong>[0,0] to [0,1]</strong> is <strong>3</strong>, hence <strong>[0,1] to [0,2]</strong> would be 3 + cost of getting to (0,1) which is 3 + 3 = 6. <br><strong>Me:</strong> Now shall we store this obtained cost corresponding to each cell in a different array, so that we can return them, when the cell is the destination?<br><strong>Friend:</strong> Fair enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*Z-bOxf1KMT6zfMGMTpoahw.png" /></figure><p>Why not code it up too?</p><pre>minarr[0][0] = a[0][0];</pre><pre>for(i=1;i&lt;n;i++)<br>  minarr[0][i] = minarr[0][i-1] + a[0][i];</pre><p>where n is the number of rows</p><p>We transfer the first element as it is to the min cost table and calculate the cost of others in the row.</p><p><strong>Friend:</strong> Why not the columns? The cells in the first column have only one way of reaching them too, which is down from the first cell.<br><strong>Me:</strong> Yeah absolutely, that’s our next step.</p><p>Similarly, we calculate the cost of reaching each column by adding the cell with the previous ones in the column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*R0ZpbAfZhfSJPO4mxaDRdw.png" /></figure><p>We’ll code that up too!</p><pre>for(i=1;i&lt;m;i++)<br>  minarr[i][0] = minarr[i-1][0] + a[i][0];</pre><p>where m is the number of columns</p><p><strong>Friend:</strong> Now, how do we calculate the minimum cost to reach cell [1,1]?<br><strong>Me:</strong> We know we can only traverse left, down or diagonally lower cell. Hence we can reach cell [1,1] only from cell [0,0] or [0,1] or [1,0]. So now that our table already has the minimum values to reach [0,0], [0,1] and [1,0], simply the minimum of those three values plus the cost of reaching cell [1,1] gives us our result.</p><p>So the cost to reach cell [1,1] = a[1,1] + min(minarr[0,0], minarr[0,1], minarr[1,0])</p><p>minarr[1,1] = 8 + min(1,3,5)<br>So, minarr[1,1] = 9</p><p>Similarly we do for all cells, starting from 1,1.</p><p>Let’s code it up again,</p><pre>for(i=1;i&lt;n;i++)<br>  for(j=1;j&lt;m;j++)<br>    minarr[i][j] = (a[i][j] + min(minarr[i-1][j-1],minarr[i][j-1],minarr[i-1][j]));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*DkNGbNSfhmW9SFwGP4Cd7A.png" /></figure><p>Now that our table is filled, we simply return the cell of the given destination in the minimum cost array. The full code is <a href="https://github.com/nobodyme/Dynamic-Programming/blob/master/minimum-cost-path.C">given here</a>. Here is a <a href="http://practice.geeksforgeeks.org/problems/largest-zigzag-sequence/0">similar problem</a>, try it on your own and another similar problem is added in the <a href="https://github.com/nobodyme/dynamic-programming/blob/master/Count-all-paths.C">repository</a>.</p><p>Hence by considering the elements one by one we have built up our solution or in DP terms we have acquired our solution in bottom up fashion(tabulation method) from the sub-problems. There’s another approach to it called memoizatation. The difference between both is explained in the <a href="http://www.geeksforgeeks.org/tabulation-vs-memoizatation/">article over here</a>.</p><h3>Longest increasing subsequence</h3><p>The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 12, 32, 2, 22, 23, 25, 30} is 6 and LIS is {10, 12, 22, 23, 25, 30}</p><p><strong>Solution:</strong></p><p>How would go on solving this problem? What would you store to make the calculations easier? Okay simply, how would you solve the above problem using <strong>brute force</strong> just like how you would perform a <a href="https://en.wikipedia.org/wiki/Selection_sort">selection sort</a>!</p><p>10 12 32 2 22 23 25 30 k,i j</p><p><strong>Friend:</strong> I would compare every element with every other element, if it’s greater than the current one, I would increase count variable and I would print the highest count, I get. Roughly I would code it something like this</p><p><strong><em>pseudo code</em></strong> (It’s okay if you don’t understand my friend’s code)</p><pre>for(i=0;i&lt;n-1;i++)<br>{   <br>  count = 1;<br>  for(j=i+1,k=i;j&lt;n,k&lt;n-1;j++)<br>  {<br>    if(a[j] &gt; a[k])<br>    {<br>      k=j;<br>  count++;<br>    }<br>    if(count&gt;maxi)<br>      maxi = count;<br>  }<br>}<br>printf(&quot;\nMax-length = %d\n&quot;,maxi);</pre><p><strong>Me:</strong> Let’s run it.<br><strong>Friend:</strong> Uh? Okay.<br><strong>Me:</strong> So what’s the output?<br><strong>Friend:</strong> The program returns, max-length = 5, which I guess is {2, 22, 23, 24, 25}. But we know it&#39;s 6 and the LIS is {10, 12, 22, 23, 25, 30}.<br>Why does it fail to catch the above lis?</p><p><strong>Me:</strong> Because while traversing {10, 12, 32, 22, 23, 25, 30} the code will run as follows,it will check,<br>if(10&gt;12) yes → count is 2, then<br>if(32&gt;12) yes → count is 3, then<br>At this point <strong>count = 3</strong>, from there on count won’t get incremented because the following elements are lesser than 32 and hence condition like (22&gt;32) will consecutively fail.</p><p><strong>Friend:</strong> If only it knew that by <strong>avoiding 32</strong> and traversing through the rest of the array we would actually obtain the result which is max-length = 6.<br><strong>Me:</strong> This is exactly the information we store for our computation using DP. In brute force terms, we store the count variable for all possible alternatives of traversal in the array and then simply find the maximum of it(Note: Not that brute force cannot solve the problem, a different approach might but definitely in exponential time).</p><p><strong>NOTE:</strong> And my friend has set count=1 and not 0 initially, because when we have a case where all numbers are same in the array i.e {2, 2, 2, 2}, we must return count as <strong>1</strong> since one element is the still a subarray of the larger one which is simply { 2 } therefore returning 0 would be wrong.</p><p><strong>Dp solution:</strong></p><p><strong>Me:</strong> So how would you code the same in dp, well actually it’s easier.<br><strong>Friend:</strong> Since you said we store counts of all variables, we initialize an array of same size of corresponding counts?<br><strong>Me:</strong> Exactly, we first start off by creating another array for storing the count for each member of the array as we discussed and initialize all of them to <strong>1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*19WcJc0qNOSJ4txW8c-G0g.png" /></figure><p><strong>Friend:</strong> Now we check in a similar way?<br><strong>Me:</strong> Yeah but for now, lets us consider only the element <strong>10</strong> exists in the array.<br><strong>Friend:</strong> Why?<br><strong>Me:</strong> To make it simpler?! Why else? Listen along. So what is the longest increasing subsequence then?<br><strong>Friend:</strong> 1 of course and LIS is {10}.<br><strong>Me:</strong> So now, say, we add 12 and set it’s initial count to 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*zmv5t1cWr4zfxWCe-840BA.png" /></figure><p><strong>Friend:</strong> We check <strong>if(12&gt;10)</strong> so 12’s count gets incremented? <br><strong>Me:</strong> Yes, now that 12&gt;10, 12’s count becomes count of 10 + 1 since count of 10 already represents the longest increasing subsequence that can be made with the existing elements. Count of 12 now represents {10} + {12} = {10 ,12} or simply count[i] = count[j]+1; which is 2</p><p><strong>Friend:</strong> So let me clear this up, when 10 was alone LIS is 1 and now that 12 is added and we find {10, 12} could be LIS since 12&gt;10 and so we add count of 10’s to 12’s count and plus 1 to include the number itself.<br><strong>Me:</strong> That’s right and the array becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*NcyPEbohPOe6fn-xg9G2Lw.png" /></figure><p>Now let us consider 32, increment i to 32 and j to 10 i.e. j to the starting element of the array and traverse from the beginning to see <strong>adding 32</strong> provides a longer subsequence. <br>The array becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*xh_qeBjA1zPayEqW2FJSoQ.png" /></figure><p><strong>Friend:</strong> Yes, it does prove longer. Since <strong>(32&gt;10)</strong> therefore we increment 32’s count → count[i] = count[j]+1;</p><p><strong>Me:</strong> We check all numbers before 32 to see if they can be added to form a sequence with it, so increment j, continue filling in the boxes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*EvQyNhfMQU9oPAiV7Ip4Tg.gif" /><figcaption>gif showing the 32’s count increment and increment on j</figcaption></figure><p><strong>Friend</strong>: Okay I will, So <strong>if(32&gt;12)</strong> → 32’s count = 12’s count + 1 = (2+1) = 3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*2D34mc1_UQtakFaRkuEKKQ.png" /></figure><p>Similarly, <strong>considering element 2</strong> the array becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*dE03Bc9slNbWm6WOjDesww.png" /></figure><p>The array stays the same since each case checking <strong>if(2&gt;10)</strong> , <strong>if(2&gt;12)</strong> or <strong>if(2&gt;32)</strong> fails, and it’s count variable remains unchanged.</p><p>Now I’m adding the next number, <strong>22</strong> and check for 10, 12, 32, similar to the previous one, for 10 and 12, count of 22 is incremented to 3 and with 32 it fails and remains as 3, and j is incremented to point 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*EjcfSofLMFsfx9vIHAFjbA.png" /></figure><p>Now <strong>if(22 &gt; 2)</strong> → count of 22 becomes count[j]+1 i.e. 2? <br><strong>Me:</strong> Haha, glad you paused and asked, in short <strong>No</strong>, we know that count reflects the longest subsequence. By traversing other elements in the array, we obtained 3 as longest subsequence for 22. So why lower it to 2? Hence while adding count[i] = count[j]+1 make sure it benefits the cause. Therefore place count[i] = max(count[j]+1,count[i]) ie with the maximum of two numbers to avoid such cases.</p><p>And similarly the rest of the array is traversed and the array becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*Xf6bsIZCrwgJJCS2brkpsw.png" /></figure><p>Since the highest is 6, that gives the longest increasing subsequence, the video of the above traversal is <a href="https://youtu.be/Ns4LCeeOFS4">linked here(different example)</a>. Let’s have a look at the code snippet of the same below. As we have learnt,</p><ul><li>We intialize count array to 1</li><li>Then calculate count for every element</li></ul><pre>for(i=0;i&lt;n;i++)<br>count[i] = 1;</pre><pre>for(i=1;i&lt;n;i++)<br>{<br> for(j=0;j&lt;i;j++)<br> {<br> if(array[i] &gt; array[j])<br>  count[i] = max(count[i],count[j]+1);<br> }<br>}</pre><p>After that we find the maximum of the count array and print it, <a href="https://github.com/nobodyme/Dynamic-Programming/blob/master/longest-increasing-sub-sequence.C">full code snippet is here</a> and a look alike problem just with a <a href="https://github.com/nobodyme/dynamic-programming/blob/master/lis-pair.C">pair of numbers</a>.</p><h3>Points to remember</h3><ul><li>Dynamic programming is just like any like any other kind you get some, you don’t get some practice makes it all better. I have lot to do too.</li><li>From my experience, it is similar to brute force but instead of exploring the whole input space, you find a way to store intermediate results that arise from the input and exhaustively explore that for the required result.</li><li>Yes, it is indeed a method of trading space for time. A recursive approach may utilize a little less space but dynamic programming approach is quicker.</li></ul><h3>Other resources</h3><ul><li><a href="https://www.hackerearth.com/practice/notes/dynamic-programming-i-1/">Hackerearth article explaining more on “Why dynamic programming”</a></li><li><a href="https://www.quora.com/What-are-some-good-ways-to-approach-a-dynamic-programming-question/answer/Paul-Baltescu">How to approach Dynamic Programming by Paul Baltescu on Quora</a></li><li><a href="http://www.geeksforgeeks.org/fundamentals-of-algorithms/#DynamicProgramming">Geeks for geeks tutorials</a></li><li><a href="https://www.hackerearth.com/practice/notes/dynamic-programming-problems-involving-grids/">Hackerearth article for problems involving grids</a></li></ul><h3>Problems lists from various sites</h3><ul><li><a href="http://practice.geeksforgeeks.org/topics/Dynamic-Programming/">Practice problems — Geeks for Geeks</a></li><li><a href="https://apps.topcoder.com/forums/?module=Thread&amp;start=0&amp;threadID=674592">Problem list — top coder</a></li><li><a href="http://codeforces.com/problemset/tags/dp?order=BY_SOLVED_DESC">Problem sets — code forces</a></li><li><a href="https://www.hackerrank.com/domains/algorithms/dynamic-programming">Dp challenges — Hackerrank</a></li></ul><p>You can find this and more of it in my <a href="https://github.com/nobodyme/dynamic-programming">github link here</a>. Hope it was of some help. Put your questions below. Maybe give me a pull request if something can be improved.<br>Feel free to <a href="https://twitter.com/_nobodyme_">follow me on twitter</a>!<br>And if you found that helpful in anyway maybe <a href="https://www.patreon.com/nobodyme">help me buy a laptop</a>, Cheers!</p><figure><a href="https://www.patreon.com/nobodyme"><img alt="" src="https://cdn-images-1.medium.com/max/217/1*i0Mh94LoR2TlVq897jKhMQ@2x.png" /></a></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36f26c2466cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/dynamic-programming-for-brute-forcers-36f26c2466cf">Dynamic Programming for Brute-Forcers</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fetch images from reddit for your desktop wallpaper, python beginners.]]></title>
            <link>https://medium.com/@naveenkumarspa/using-python-for-your-desktop-wallpaper-collection-focused-on-beginners-a66451d25660?source=rss-65beee3faf68------2</link>
            <guid isPermaLink="false">https://medium.com/p/a66451d25660</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Naveen]]></dc:creator>
            <pubDate>Sat, 14 Jul 2018 11:31:40 GMT</pubDate>
            <atom:updated>2019-05-08T07:21:57.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xU-Q53EyH086_lZCrBV7Nw.png" /><figcaption>One such wallpaper from reddit</figcaption></figure><p><em>“There’s always somebody who’s just began who you can help and there’s always somebody who did the same mistake and can help you”.</em></p><p>Just when I let that sink in, I called up my friend who wanted some wallpapers for her newly installed Ubuntu system. Me being the frequent lurker on reddit loved the pictures in subreddits like <a href="https://www.reddit.com/r/itookapicture/">itookapicture</a>, <a href="https://www.reddit.com/r/CozyPlaces/">cozyplaces</a> and <a href="https://www.reddit.com/r/wallpapers/">wallpapers</a> and wrote up a simple program to grab those and then set up as Desktop-slideshow using an app called <a href="http://shotwell-project.org/doc/html/">Shotwell</a> when I was in the same position. So I just sent her over the link of the <a href="https://github.com/nobodyme/reddit-fetch">repo from github</a>, while she was more than pleased to have it, she wanted to know how it does as well. I thought to myself, well she already knows basics of python so it mustn&#39;t be that hard. So I started off with <em>“so clone the github repo and then do pip3 install -r requirements.txt, oh maybe use the virtualenv as well, so you don’t install the packages globally but just for the project and then we call the reddit’s open-api …“</em> and I realized she was already left scratching her head even before the coding part began.</p><p>That’s when I realized I was in the same page as well, I couldn&#39;t even understand how all the code came together even when I was given the link to the github repo few years back. I wouldn&#39;t know where to start, why certain things are done, blindly follow instructions and wouldn&#39;t know how to fix it when it breaks. So for all you folks out there who just started learning python variables, if conditions, switch statements and for loops from some website, maybe this article will help you fill the missing parts that’ll get you going.</p><p>So what do we have on our plate?</p><p>All we need to do is ask reddit to give us the pictures from the subreddits we want so that we could store them somewhere in a file and later use shotwell for slideshow.</p><p>But how do we do that?</p><h3>Understanding APIs and JSON</h3><p>What happens generally when you go to a link is that, your browser will send a request to the server like, <em>“Hey, can I wanna see the contents on this one, send this to me as HTML, please”</em> and then server responds to the request as a HTML page like the one you’re viewing right now because HTML is more friendly to humans. But we want our program to fetch the pictures right? So we need a response that’s friendly to parse by code but how does our program talk to the reddit server? We want a interface which our program can talk to, just like we do through our browser. This is called an <strong>API (application programming interface)</strong> and every application these days have an interface where programs can talk to and fetch information, some publicly available, some private, some available with paid subscriptions for their services. What this API commonly returns is data in a format called <strong>JSON</strong> which stands for Javascript Object Notation and it is this format that our program will be easily able to parse and get us our wallpapers and it is just a bunch of key, pair values similar to a dictionary in python which you will all be familiar with.</p><p>So how do I get this JSON data from reddit?</p><p>It’s easier than you think, reddit follows the <a href="https://en.wikipedia.org/wiki/Open_API">OPEN-API standard</a> and just placing .json after the link gives you all of the data in JSON format, maybe try this in your browser <a href="https://www.reddit.com/r/wallpapers.json">https://www.reddit.com/r/wallpapers.json</a> those random data that you see is exactly what we need and if you look closely it will have all the information that you see on the web page in the form of a python dictionary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWXEspsNZwQFieM-cJBt4A.png" /><figcaption>Json data from reddit prettified using firefox</figcaption></figure><p>Now how do we obtain that data in code? Simple, just import the requests library,</p><pre>import requests<br>url = ‘https://www.reddit.com/r/wallpapers.json&#39;<br>response = requests.get(url)<br>if not response.ok:<br> print(“Error”, response.status_code)<br> exit()<br>data = response.json()<br>print(data)```</pre><p><a href="http://docs.python-requests.org/en/master/">Requests</a> library just simplifies these HTTP calls for you, requests a url returns a request object with a bunch of information which we can use to know if the request was successful, like we can ask, Was the response ok(200)? Can we parse the data now? If not we can code our program to fail silently. That should print the data you saw on the browser right in your terminal or nope you would probably get an error stating <strong>“No module named requests” </strong><em>(or if you already have requests installed you would get a “Too many requests, error 429” which we will be handling down the line. Either way it’s good that you follow along without skipping to that)</em></p><p>Well if you google, you’d come up with something like do,</p><p>sudo pip install requests</p><p>That sure works, but what this does is, it install the requests library globally for your system. You’d think it’s convenient since it will be available for another program that uses requests as well, you wouldn&#39;t have to run the command again but think about the case where different programs use different versions of the same library. That’s a conflict you do not want to handle plus let’s say you’re sharing this code to a friend of yours or posting it on github, you would ideally like to have a list of the packages/libraries your code depends on, so to say, <em>“Hey, this is the list of packages you will need to run my code, so just install these”</em>. Convenient right? So that’s what we will do.</p><h3>Understanding VIRTUALENV and PIP</h3><ol><li>We need an isolated environment where we can install libraries just for our program.</li><li>We will then need the list of libraries our code uses along with the exact version so that we can share it along with our code.</li></ol><p>So let’s try and install something called a virtualenv, which let’s us create this nice comfortable isolated environment for our program. <em>Of course you could also use </em><a href="https://docs.pipenv.org/"><em>pipenv</em></a><em>.</em></p><p>So if you’re on ubuntu do follow the instructions below, if you’re on windows or mac you could <a href="https://packaging.python.org/guides/installing-using-pip-and-virtualenv/">try this link here</a>.</p><pre>sudo apt-get install virtualenv <br>sudo apt-get install python3-pip</pre><p>PIP is the recursive acronym for “Pip install Packages” commonly used for installing python packages or libraries. So since both pip and virtualenv is installed, lets set-up our development environment for our program.</p><p>Go to the project folder and then type,</p><pre># creates directory called env <br>virtualenv -p python3 env</pre><pre># activates the env directory so that our program&#39;s packages will be installed in it<br>source env/bin/activate</pre><p>You should see a (env) sign before your prompt, if so, we are good to go.<br>Now that our development environment is setup, let’s install the requests package.</p><h3>Installing requests module</h3><pre>pip3 install requests</pre><p>Now this will place the package and it’s dependencies in the local folder. Great we have our package installed isolated for our program.</p><p>Now if we want to list the packages our program depends on, we can just do,</p><pre>pip3 freeze &gt; requirements.txt</pre><p>This lists out all the dependencies and puts it into a file called requirements.txt. So now you can send over this file and say, <em>“Hey just install the ones in these files and my program will work fine”</em>.</p><p>Just in case you want to install your friend’s program and he has sent you his file of dependencies, you can just do that by,</p><pre>pip3 install -r requirements.txt</pre><p>Suppose you want to go outside our program’s environment, you can just do type, “deactivate” at the prompt.</p><h3>Edge Cases</h3><p>So now that we have installed requests and everything is set, let’s run our program.</p><p>You would either see the data printed on your terminal or you would probably be greeted with this error message on testing for quite a while <strong>{‘message’: ‘Too Many Requests’, ‘error’: 429}</strong>.</p><p>There are certain limits on how much you can access the reddit API and your python code sets up some default user-agent for accessing the API. Since many people would probably use the default one, you quickly run out with the number of times you can request the data and that error is just reddit’s way of telling you, <em>“Hey, you’re sending too many requests my way”</em>. There are two ways to mitigate that,</p><ol><li>You can set up a custom header when you request data from the API like, response = requests.get(url, headers={&#39;User-agent&#39;: &#39;your-bot-name 0.1&#39;})</li><li>Or use the <a href="http://praw.readthedocs.io/en/stable/getting_started/quick_start.html">reddit’s PRAW library</a> by creating client ID and app ID with reddit.</li></ol><p>Although the second one is easier in the long run. For the purpose of our application we will stick with the former.</p><p>Now that we reliably get the data, let’s see how we can parse it for the information we need. We basically need the image’s url so that we can use it to download the picture. As we already know, JSON data is similar to a dictionary. So just searching for URL in the data and it’s location should help you understand how to obtain it.</p><pre># array of posts in the page<br>data = response.json()[&#39;data&#39;][&#39;children&#39;]<br># get first post from array of posts<br>first_post = data[0][&#39;data&#39;]<br># get the image url of the first post<br>image_url = first_post[&#39;url&#39;]</pre><p>Now that we have the url of the image, let’s download that and store it in a file as well.</p><pre>image = requests.get(image_url)<br>if(image.status_code == 200):<br>    output_filehandle = open(&#39;image1.jpg&#39;,mode=&#39;bx&#39;)<br>    output_filehandle.write(image.content)</pre><p>Now we have got the image of the first post in the page. Depending upon a number of things our application could break resulting in an error.</p><p>If you look closely we have assumed that the image is of the type “jpg”, secondly we assume that a file called “image1.jpg” is not already present. Now although the first case might not throw you an error, you won’t be able to open up the image since it may not be of the right format and the second case will throw<strong> <em>file already exists</em></strong> error. And for our application we are going to have the tile of the post as the file name of our image.</p><p>So our code now looks like,</p><pre>import requests<br>url = &#39;https://www.reddit.com/r/wallpapers.json&#39;<br>response = requests.get(url, headers={&#39;User-agent&#39;: &#39;your-bot-name 0.1&#39;})<br>if not response.ok:<br>    print(&quot;Error&quot;, response.status_code)<br>    exit()<br>data = response.json()[&#39;data&#39;][&#39;children&#39;]<br>first_post = data[0][&#39;data&#39;]<br>image_url = first_post[&#39;url&#39;]<br>image = requests.get(image_url)<br># checks url and sets appropriate extension for the image file<br>if &#39;.png&#39; in image_url:            <br>    extension = &#39;.png&#39;        <br>elif &#39;.jpg&#39; in image_url or &#39;.jpeg&#39; in image_url:            <br>    extension = &#39;.jpeg&#39;<br>if(image.status_code == 200):<br>    try:<br>        output_filehandle = open(first_post[&#39;title&#39;] + extension, mode=&#39;bx&#39;)<br>        output_filehandle.write(image.content)<br>    except:<br>        pass</pre><p>Now your program may work or may not still work as intended as we have two other edge cases to handle which you will only discover when you have tried different sets of data. If your program currently doesn&#39;t work good for you, you have a set of data that presents you the edge case right at the beginning. Yes, it’s better you stumble upon these at first than build everything and wonder what went wrong. So what’s the error?</p><p>The problem with these image links is that a lot of times image links on reddit are from <strong>imgur</strong> and <strong><em>sometimes</em></strong> imgur links don’t open up as image files but rather as a page with collection of images. Try the blow URLs yourself.</p><ol><li>Normal url: <a href="https://i.redd.it/qcqy40krxn911.png">https://i.redd.it/qcqy40krxn911.png</a> (or .jpeg with extensions)</li><li>Imgur url: <a href="https://imgur.com/zXpT3vJ">https://imgur.com/zXpT3vJ</a></li></ol><p>Therefore in the second case, your program will try to download the HTML file as binary. On trail and error by opening the image on a new tab or by appending “.jpeg” to the URL you will find that it opens up as an image file just like the others, if it already doesn&#39;t open as one.</p><p>And sometimes the images uploaded are <strong>removed</strong> as well, the link will direct to a thumbnail denoting the image has been removed. We don’t want that to clutter our list of wallpapers. So let’s handle these cases in our code as well.</p><pre>import requests<br>url = &#39;https://www.reddit.com/r/wallpapers.json&#39;<br>response = requests.get(url)<br>if not response.ok:<br>    print(&quot;Error&quot;, response.status_code)<br>    exit()<br>data = response.json()[&#39;data&#39;][&#39;children&#39;]<br>first_post = data[0][&#39;data&#39;]<br>image_url = first_post[&#39;url&#39;]<br>if &#39;.png&#39; in image_url:            <br>    extension = &#39;.png&#39;        <br>elif &#39;.jpg&#39; in image_url or &#39;.jpeg&#39; in image_url:            <br>    extension = &#39;.jpeg&#39;<br>else:            <br>    image_url += &#39;.jpeg&#39;           <br>    extension = &#39;.jpeg&#39;<br># prevents thumbnails denoting removed images from being downloaded<br>image = requests.get(image_url, allow_redirects=False)<br>if(image.status_code == 200):<br>    try:<br>        output_filehandle = open(first_post[&#39;title&#39;] + extension, mode=&#39;bx&#39;)<br>        output_filehandle.write(image.content)<br>    except:<br>        pass</pre><p>Now your code should work perfectly for all cases and now you check the image file that’s downloaded. Since we have successfully downloaded image of the first post, let’s do that for all posts. By default we get a list of 25 posts for more posts say 100, we could modify the url as,</p><pre>url = &#39;<a href="https://www.reddit.com/r/wallpapers.json?&amp;limit=10">https://www.reddit.com/r/wallpapers.json?&amp;limit=10</a>0<a href="https://www.reddit.com/r/wallpapers.json&#39;">&#39;</a></pre><p>Now that our url is set let’s loop over all posts to retreive all images.</p><pre>import requests<br>url = &#39;https://www.reddit.com/r/wallpapers.json?limit=100&#39;<br>response = requests.get(url)<br>if not response.ok:<br>    print(&quot;Error&quot;, response.status_code)<br>    exit()<br>data = response.json()[&#39;data&#39;][&#39;children&#39;]<br>for i in range(len(data)):<br>    current_post = data[i][&#39;data&#39;]<br>    image_url = current_post[&#39;url&#39;]<br>    if &#39;.png&#39; in image_url:            <br>        extension = &#39;.png&#39;        <br>    elif &#39;.jpg&#39; in image_url or &#39;.jpeg&#39; in image_url:            <br>        extension = &#39;.jpeg&#39;<br>    elif &#39;imgur&#39; in image_url:            <br>        image_url += &#39;.jpeg&#39;           <br>        extension = &#39;.jpeg&#39;        <br>    else:            <br>        continue<br>    image = requests.get(image_url, allow_redirects=False)<br>    if(image.status_code == 200):<br>        try:<br>            output_filehandle = open(current_post[&#39;title&#39;] + extension, mode=&#39;bx&#39;)<br>            output_filehandle.write(image.content)<br>        except:<br>            pass</pre><p>Now that’s it, we have got our sets of images downloaded and I added the else part so that the program doesn&#39;t break for cases that we still haven’t encountered. Now that you have the pictures downloaded you can now use Shotwell to <a href="http://shotwell-project.org/doc/html/share-background.html">setup a desktop slideshow</a> by selecting all of these images in your machine.</p><h3>Conclusion</h3><p>But as you know ideally we would want to supply data to the program as a user, we can’t keep modifying the program if we wanted pictures from a different subreddit or more number pictures. Personally, I would even like to supply a series of subreddits to fetch from at a point and download each in a separate folder.</p><p>There are few other edge cases that you would face while handling different sets of data as well. For example, we set the file name to the title of the post, sometimes the titles may contain special characters which might not be a accepted file name format in your operating system. Sometimes the title might be too long that your OS doesn&#39;t permit it as a valid file name.</p><p>You would see all of these improvements handled right here, in my <a href="https://github.com/nobodyme/reddit-fetch/blob/master/grab_pictures.py">code on github</a>. I will also post a snippet below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcb2f1a7f7360eaef813e60ed49513e0/href">https://medium.com/media/dcb2f1a7f7360eaef813e60ed49513e0/href</a></iframe><p>You will also find a similar program which fetches the <a href="https://github.com/nobodyme/reddit-fetch/blob/master/fetch_comments.py">comments of a reddit post</a> in a file in the same repo. Hope it is of some help. Put your questions below. Maybe give me a pull request if something can be improved. Cheers!<br>Feel free to <a href="https://twitter.com/_nobodyme_">follow me on twitter</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a66451d25660" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>