<?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 Ben Glanton on Medium]]></title>
        <description><![CDATA[Stories by Ben Glanton on Medium]]></description>
        <link>https://medium.com/@glantonb?source=rss-bb9a2cd23af3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R6QY7ik830Kx2D6h0kLV_Q.jpeg</url>
            <title>Stories by Ben Glanton on Medium</title>
            <link>https://medium.com/@glantonb?source=rss-bb9a2cd23af3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:55:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@glantonb/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[Well Euled Machines — 5]]></title>
            <link>https://medium.com/@glantonb/well-euled-machines-5-a7998f2bf5b6?source=rss-bb9a2cd23af3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7998f2bf5b6</guid>
            <category><![CDATA[coding-standards]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[coding-standards-python]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ben Glanton]]></dc:creator>
            <pubDate>Tue, 08 Mar 2022 00:44:16 GMT</pubDate>
            <atom:updated>2022-03-08T00:44:16.665Z</atom:updated>
            <content:encoded><![CDATA[<h3>Well Euled Machines — 5</h3><p>5 of 5 — In which we wedge a generator in there somehow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*IQUVINWHwY7r8Ik6JOODbQ.png" /><figcaption><em>The Python Logo (Two stylized snakes form a + sign. The word ‘python’)</em></figcaption></figure><p>This is the last of a set of articles intended to help developers who are converting over to Python. This part does not require that you have read the previous articles. There is an assumption that you have some experience of programming, probably with one of the common imperative languages.</p><p><a href="https://projecteuler.net/">Euler Problems</a> are quick challenges. Each challenge asks you to write a program to solve some problem. A good solution should run in under a minute — but it might take an hour or two to write a 1-minute program. You can learn quite a lot by doing the first few Euler problems. <a href="https://projecteuler.net/problem=5">Euler Problem 5</a>, was the first puzzle that I really enjoyed writing, and where I had to think for a bit to come up with a fast enough solution:</p><blockquote><em>2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.</em></blockquote><blockquote><em>What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?</em></blockquote><h3>What We’ll be Doing</h3><p>This article is less “here’s a cool feature in Python” than the previous articles. As the last article in the series (and thanks for taking the time if you’ve read all the way here) it’s more about what’s <em>good </em>Python. As a bonus there there’s not one, but two cool features, and one of them pays off on my promise to show you a little about Python’s <em>generator</em> feature.</p><h3>Solving the Problem</h3><p>There’s a well established algorithm for doing this. You might recall from an earlier item that there is exactly one Prime Factorization for every number — the set of prime numbers that multiply together to make that number. If you wonder about factorizing 1 you should talk to a <a href="https://www.quora.com/What-is-the-prime-factorization-of-1">mathematician</a>.</p><p>The algorithm is easiest to follow from an example — so let’s do the whole thing for 10. The Prime Factorizations are as follows:</p><p><strong>2</strong>: {2}</p><p><strong>3</strong>: {3}</p><p>4: {2 × 2}</p><p><strong>5</strong>: {5}</p><p>6: {2 × 3}</p><p><strong>7</strong>: {7}</p><p>8: {2 × 2 × 2}</p><p>9: {3 × 3}</p><p>10: {2 × 5}</p><p>In our example 8 and 6 are important to look at. We’ve been reminded that 8 is ‘made’ of 3 ×2’s, so when we mix-up a solution at the end, as we put an 8 in the mix we’ve already included all the 2’s and 4’s we’ll need — if we added them again then we’d be failing in the part of the question that requires the <em>smallest </em>valid number.</p><p>6 is interesting. It’s the first number compounded of 2 different primes. Without diving into a full proof: if you have at least one of each of 2 &amp; 3 making up a 6 then you can multiply by as many more as you like and always get a multiple of 6. So we have to ensure there’s <em>at least </em>one of each in our solution.</p><p>We need to combine the set of factorizations that we already built. We need to ensure we have just enough, but not more, of each of the primes to produce every number from 1 to 10.</p><p>That is achieved by finding the maximum occurrences of each prime in any one of those sets, and then multiplying them together. In this case that looks like:</p><p>(2 × 2 × 2 ) × (3 × 3) × 5 × 7 = 2,520.</p><h3>How to Generate Primes</h3><p>In a previous example we generated prime numbers using a simple Python function. We’ve already learned the way Python treats functions differs from other languages. Here’s a <em>really </em>different way to think about functions.</p><p>A Function in Python that uses <em>yield</em> in place of <em>return </em>stops being a function. Now it’s a generator. When a function returns it is cleared out of memory. When a generator yields it stops running, for a bit. You use it a little differently, you need to call <em>next() </em>on a generator, each time you do that the ‘function’ wakes back up and runs until it has something new to yield.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63804fa76aadd2891eee26663035550f/href">https://medium.com/media/63804fa76aadd2891eee26663035550f/href</a></iframe><p>This gist is close to the standard prime generator I use in puzzles. It still has some inefficiency for you to work on, but for this puzzle we need very few primes and it is fine.</p><h3>Prime Factorization</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48dfadcaad238f1a7a47bd66b8bd25b0/href">https://medium.com/media/48dfadcaad238f1a7a47bd66b8bd25b0/href</a></iframe><p>Your second Cool Python Trick is at line 3. The Factors are stored in a <em>defaultdict</em> which gives us interesting behaviour. You can test that in the Python REPL like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78a7f1815926073d43db7d7e1ad9d140/href">https://medium.com/media/78a7f1815926073d43db7d7e1ad9d140/href</a></iframe><p>Defaultdict adds new behaviour to an otherwise normal dictionary, we can associate values with keys, and retrieve them later. We can interrogate it about whether it contains a key. Ordinarily in Python if we learned that a dictionary had no ‘fish’ in it but we demanded ‘fish’ anyway, then today&#39;s dish is not fish. Today&#39;s dish is a KeyError, and the program will stop working right about there.</p><p>With a defaultdict, when we request a value that isn’t present it will be created. In this case we asked for an int, we get 0 as the default value. Asking for list or dict is pretty common . Empty instances are provided in those cases.</p><h3>Put it Together</h3><p>There isn’t a great deal of complexity to generating the complete set of factorisations for numbers and then combining them. Some very minor notes — at line 34 we use <em>** </em>for exponentiation, which limits my ability to use footnotes*. At line 22, while generating the set of Primes we use the Walrus Operator because it’s got a great name, and because being able to store the value we’re generating in the loop-step saves us a line of code while <em>adding </em>clarity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecf2ec0a1b6e32fa27d5c259c347231c/href">https://medium.com/media/ecf2ec0a1b6e32fa27d5c259c347231c/href</a></iframe><h3>But There’s More</h3><p>The structure of code is a big part of writing self-documenting code. We break code down into parts that can be readily explained. When we give those functions names we’re already writing documentation — sometimes all the description we need is in the name; most of the time I think it’s wise to add a doc-string, at minimum. Whenever we think adding documentation to explain something that’s a sign we might need to break out a function.</p><p>Consider this version of the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c6f27a1d369003a5d2a92b080855362/href">https://medium.com/media/2c6f27a1d369003a5d2a92b080855362/href</a></iframe><p>I think the naming here is better than the code we developed throughout thie article. It’s always had really short functions, with names that make some sense, and a couple of doc-strings.</p><p>I would probably mark it as needing serious improvement if it were created professionally. In this contrived example, take a look at line 37. We have a comprehension building a dictionary, based on a comprehension derived from a list of dictionaries. That’s somehow more tiresome to type than to read, but I’m sure that’s the right description! This code is being clever.</p><p>Google is a clever company. Google’s coding standards are a gold standard and as a guideline allow for a single level of nested comprehension. Nevertheless, I think that even at Google this line of code would go back for re-writes at review. Even with it being the only line of code represented by the name `combine_prime_factors` it’s still hard to follow. (Full disclosure I developed in stages to get this right). This is spaghetti code crammed into one line!</p><p>At the heart of using Python well is taking proper advantage of its highly geared nature. You can get a lot of work out of just a few lines of code. Part of that is that Python eliminates a lot of the boilerplate in other languages. The rest is that Python simply is more powerful line-for-line than most languages. When you can go faster you’ll reach your destination more quickly. If you stay on track. When you get lost in the jungle though, Python is very good at hiding meaning.</p><p>* <em>I can have exactly one, since ** would be ambiguous.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7998f2bf5b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Well Euled Machines — 4]]></title>
            <link>https://medium.com/@glantonb/well-euled-machines-4-b381930ab7b?source=rss-bb9a2cd23af3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b381930ab7b</guid>
            <dc:creator><![CDATA[Ben Glanton]]></dc:creator>
            <pubDate>Sun, 27 Feb 2022 18:02:49 GMT</pubDate>
            <atom:updated>2024-08-08T00:51:30.192Z</atom:updated>
            <content:encoded><![CDATA[<h3>Well Euled Machines — 4</h3><p>4 of 5 —A little slice of Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*IQUVINWHwY7r8Ik6JOODbQ.png" /><figcaption><em>The Python Logo (Two stylized snakes form a + sign. The word ‘python’)</em></figcaption></figure><p>This is the fourth in a series of stories to help developers who are converting over to Python. There is a thread running through them, but this article doesn’t depend on previous articles.</p><p><a href="https://projecteuler.net/">Euler Problems</a> are quick challenges. Each challenge asks you to write a program to solve some problem. A good solution should run in under a minute — but it might take an hour or two to write a 1-minute program. You can learn quite a lot by doing the first few Euler problems. <a href="https://projecteuler.net/problem=4">Euler Problem 4</a> does word-things with numbers, so we can look at some everyday features; converting between types, and some ways of working with lists. Towards the end we’ll look at ‘slices’, which are an immensely useful tool.</p><p>Euler Problem 4 is:</p><blockquote><em>A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.</em></blockquote><blockquote><em>Find the largest palindrome made from the product of two 3-digit numbers.</em></blockquote><h3>How to approach the problem</h3><p>The challenge Euler have set us is in two parts. Most obviously we need to work out if a number is palindromic, which will be the body of this story. There’s a second, fun, challenge in finding a way to work out the <em>biggest</em> palindromic number part efficiently. On a modern computer this is reasonable to brute-force. There are 899 three-digit numbers, so there are 808,201 combinations of two numbers to check.</p><p>Faster solutions are available if you think of the two numbers as being x, y coordinates on an 899-sized sheet of grid-paper. As an exercise for the reader, you can look for efficient ways to search starting at 899 × 899 and work in a spiral that sticks near that corner to find the biggest palindrome first of all.</p><p>This story just sticks with the palindrome bit.</p><h3>Reversing a string the ‘obvious’ way</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/989494fa1352ed4e49d88015642db076/href">https://medium.com/media/989494fa1352ed4e49d88015642db076/href</a></iframe><p>Will print ‘sdrawrof’, you might not be surprised, and I understand that. Here’s what’s going on.</p><p>We passed the input string ‘forwards’ to a function called <em>reversed()</em>. Under the hood Python already treats strings as being container types, so reversed did not give us a string back, it provided a kind of list of letters.</p><p>The ‘reversed’ class is enough like a list that it can be iterated over, so to get back a printable string we are using a function called ‘join’, with the empty string as a parameter. That says connect every string of the reversed word with the empty string as the glue.</p><p>If you invoked <em>join() </em>as<em> ‘, ’.join(reversed(‘forward’)) </em>you would get “d, r, a, w, r, o, f” which just hints at how useful <em>join()</em> can be<em>.</em></p><h3>Converting to String</h3><p>Python makes that quite easy — <em>str(some-number)</em> will convert to the string representation of the number, defaulting to base-10.</p><h3>Putting it together</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a93d05f35bc59282d2cadf507fa274e/href">https://medium.com/media/3a93d05f35bc59282d2cadf507fa274e/href</a></iframe><p>This function will take in a variable, convert it into a string and then check if the string is the same forwards as backwards. It is pretty simple to see how it maps to the problem statement.</p><h3>Slicing it up</h3><p>If you have a container that can be treated like a list you can access items using square brackets: ‘<em>forwards’[0]</em> is f. But<em> ‘forwards’[3:7]</em> is ‘ward’ and<em> ‘forwards’[6:2:-1]</em> is ‘draw’, because we’re stepping -1 letter each time.</p><p>The arguments in a slice are options, ignore stop and you take everything <em>from </em>some point in the list, ignore <em>step </em>and you default to stepping forward 1 each time. That means you can reverse a string with [::-1]. That’s cryptic until you get used to slices, and very useful once you do. It can be read as “start at the back, work your way to the front one character at a time.”</p><p>So one good candidate solution for checking is a string is a palindrome might look like:</p><p><a href="https://gist.github.com/glantonb/1970ceb0c004c480a6856a6bb4c9499e.js">https://gist.github.com/glantonb/1970ceb0c004c480a6856a6bb4c9499e.js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b381930ab7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Well Euled Machines -3]]></title>
            <link>https://medium.com/@glantonb/well-euled-machines-3-c6d6023dd9aa?source=rss-bb9a2cd23af3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6d6023dd9aa</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[good-programming-practice]]></category>
            <dc:creator><![CDATA[Ben Glanton]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 15:55:22 GMT</pubDate>
            <atom:updated>2024-08-08T00:38:58.600Z</atom:updated>
            <content:encoded><![CDATA[<h3>Well Euled Machines — 3</h3><p>3 of 5 — This weird trick Python has</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*IQUVINWHwY7r8Ik6JOODbQ.png" /><figcaption><em>The Python Logo (Two stylized snakes form a + sign. The word ‘python’)</em></figcaption></figure><p>This is the third of a set of articles intended to help developers who are converting over to Python. You don’t need to have read the first parts.</p><p><a href="https://projecteuler.net/">Euler Problems</a> are quick challenges. Each challenge asks you to write a program to solve some problem. A good solution should run in under a minute — but it might take an hour or two to write a 1-minute program. You can learn quite a lot by doing the first few Euler problems. <a href="https://projecteuler.net/problem=3">Euler Problem 3</a>, is a good chance to talk about some ‘sugar’ Python adds to its syntax.</p><blockquote><em>The prime factors of 13195 are 5, 7, 13 and 29.</em></blockquote><blockquote><em>What is the largest prime factor of the number 600851475143 ?</em></blockquote><h3>There’s an XKCD for this</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*h9Ms9f4z6eeGEDN1XfA31w.png" /><figcaption><a href="https://imgs.xkcd.com/comics/ten_thousand.png">https://imgs.xkcd.com/comics/ten_thousand.png</a></figcaption></figure><p>In that spirit, and because I’ve learned from my colleagues that you can like doing programming challenges, but hate doing mathematics, here’s a quick refresher/intro to what you need to know for at least one solution to Euler Puzzle 3.</p><h3>Primes</h3><p>A prime number is any number larger than 1 that can only divide equally by itself and 1 (*). The first prime numbers are 2, 3, 5, 7, 11, 13 and 17. They are wildly useful for many maths-adjacent purposes like cryptography (and therefore cryptocurrency and NFTs!).</p><p>The factors for X are the numbers that divide evenly into X. If X is 12, then that would be {1, 2, 3, 4, 6, 12}. Prime factors are any of those divisors that are also prime. For 12 the prime factors are {2,3} because 12 = 2 × 2 × 3.</p><h3>The Sieve of Eratosthenes</h3><p>Eratosthenes (Era-toss-theh-knees) of Cyrene lived around 200 B.C.E. He was primarily a geographer — one of the first people to measure the size of the Earth with any accuracy. His algorithm was the best way to find prime numbers for hundreds of years. It is <a href="https://github.com/PlummersSoftwareLLC/Primes">still used</a> to measure computer <a href="https://www.youtube.com/watch?v=D3h62rgewZM">horsepower</a> now.</p><p>It is taught at school as: write down a number line. Cross out 1. 2 is the first number you are left with, cross out every second number, add 2 to the the list of primes. 3 is the first number you are left with, cross out every third number, add 3 to the list of primes. 5 is the first number you are left with…</p><p>There is a good Wikipedia <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">article</a> which draws the algorithm — it’s always useful to be able to visualize an algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*ZCDjSI5Qnc4Xah6VfqB_9Q.gif" /><figcaption><a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#/media/File:Sieve_of_Eratosthenes_animation.gif">https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes</a></figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#/media/File:Sieve_of_Eratosthenes_animation.gif">Sieve of Eratosthenes - Wikipedia</a></p><p>The rest of this article talks about how to produce a list of prime numbers. For our purposes we will slightly alter the algorithm. We will create a list with only the number 2 in it. We will then start counting up candidate numbers from 3; we will check if each candidate is divisible by any of the primes we know about. If it isn’t we have found a new prime. We will add that to our list, so from now on each candidate is checked against one more number**</p><h3>This one weird Python trick</h3><p>The following gist will generate a list of prime numbers below some value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af046e476bd4882716720683e5b255e7/href">https://medium.com/media/af046e476bd4882716720683e5b255e7/href</a></iframe><blockquote>That code is <em>not</em> good enough to go solving Euler 3 quickly enough. We are being asked to find the prime factors of 600 <em>billion</em> and change. This naïve solution will try to count to 0.6 trillion before it decides it has run out of candidate numbers to check.</blockquote><blockquote>We can actually stop at the square root of <em>range_max </em>and know that we haven’t missed any factors. Like printing the results of <em>primes_below </em>and calling it, that speed-up is left as an exercise for the reader. This article is interested in the ‘syntactic sugar’ Python adds by thinking about all the things ‘else’ could mean.</blockquote><p>Take a look at line 17. Doesn’t that look a bit odd? Python uses indentation extensively, how is it getting from the ‘if’ at line 14 connected to the ‘else’? The answer is that it does not. The ‘else’ block actually belongs to the for-loop started at line 13.</p><p>Python allows ‘else’ to belong to a couple of things other language designers didn’t think of: you can have an else attached to if-statement, for-loops, while-loops and exception catches too. The behaviour of a for-else loop is that it will trigger only if there wasn’t a <em>break</em> in the for-loop, so in our case if we didn’t find an existing prime-factor for our candidate number, we go into the else block and deal with the new prime number we found.</p><p>The general use-case for this Python feature is just that. For-else loops are best used to deal with a search behaviour. We do for-each on some collection, probably a list where we want to find the one needle in the haystack. If we find a needle we immediately break, saving us from searching the rest of the haystack. The <em>else </em>block can be considered as “do this if you never find a needle”.</p><p>The for-else block, like the list-comprehension from the first story in this series is quite powerful. Any time you are using more than one or two in close proximity, or especially when nesting them, consider adding a comment to explain to anyone reading the code what they mean.</p><blockquote><em>So this one time I got pulled into a discussion between another, senior, member of my team and a really capable consultant who’d just pushed a PR that contained a nested set of for-else loops. I was asked to decide whether the code was actually-correct or just correct-for-the-tests-we-have. I was pretty sure it was good after a minute or two reading, until the permie developer came up with a really good edge case. Cue 3 of us all working on one virtual whiteboard for another 20 minutes.</em></blockquote><blockquote><em>You can make code simple by using the right features — fewer lines of code are </em>nearly <em>always</em> <em>better lines of code, but only nearly. Simple, fast-enough, solutions following the lines of the problem are best of all. Try to avoid nesting for-else loops and do try to stick to using them in the search success/not-found handling pattern if you can.</em></blockquote><p>*<em>If you did mathematics long enough ago, that definition might have changed on you. 1 used to be considered prime for some purposes, or prime-adjacent or something. That poses a problem! It’s a foundational idea that for any number there is only one way to break it down into a set of prime factors. Multiplying a number by 1 doesn’t do anything. Since it does nothing, we can do it as many times as we’d like: so we don’t have a </em>unique <em>set of prime numbers, mutiply-by-1 could be there 0, 1, 2, …infinite times.</em></p><p><em>**For the interested — “why do we only check the candidate number against </em>prime<em> numbers I already know about, why not every number?”. That goes back to the fundamental theorem — all numbers are made up by multiplying together 1-or-more prime numbers. Necessarily each of the primes that multiply to make x must be smaller than </em>x<em>. Therefore non-prime numbers will have been tested by proxy once we tested each of the smaller prime numbers that multiply together to make them.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6d6023dd9aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Well Euled Machines - 2]]></title>
            <link>https://medium.com/@glantonb/well-euled-machines-3c2277e42b03?source=rss-bb9a2cd23af3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c2277e42b03</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learn-code]]></category>
            <dc:creator><![CDATA[Ben Glanton]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 23:58:54 GMT</pubDate>
            <atom:updated>2024-08-08T17:06:16.591Z</atom:updated>
            <content:encoded><![CDATA[<h3>Well Euled Machines — 2</h3><p>2 of 5 — Together we learn a little about how Python ‘thinks’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*IQUVINWHwY7r8Ik6JOODbQ.png" /><figcaption><em>The Python Logo (Two stylized snakes form a + sign. The word ‘python’)</em></figcaption></figure><p><em>This is the second of a set of articles intended to help developers who are converting over to Python. You don’t need to have read the </em><a href="https://medium.com/@glantonb/well-euled-machines-575bdbc195d8"><em>first part</em></a><em>.</em></p><p><a href="https://projecteuler.net/">Euler Problems</a> are quick challenges. Each challenge asks you to write a program to solve a small problem. A good solution should run in under a minute — but it might take an hour or two to write a 1-minute program. You can learn quite a lot by doing the first few Euler problems. The <a href="https://projecteuler.net/problem=2">second</a> problem is a chance to engage with Python’s docs, and learn about a feature called ‘decorators’.</p><blockquote><em>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</em></blockquote><blockquote><em>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …</em></blockquote><blockquote><em>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</em></blockquote><p>Euler Problem 2 is another common programming challenge. <a href="https://mathshistory.st-andrews.ac.uk/Biographies/Fibonacci/">Fibonacci</a> (actually a stage name. Maths used to be something done competitively, for prizes, in front of an audience!) is another colourful and important historical mathematician to go with Leonhard Euler. This series shows up all over nature, and in Agile planning poker!</p><p>After the last article, there’s no challenge to ‘sum these numbers’ , or deciding if a number is divisible by 2. We’re will focus on how to <em>efficiently</em> compute Fibonacci numbers efficiently.</p><blockquote>In a <a href="https://medium.com/@glantonb/well-euled-machines-5-a7998f2bf5b6">later article</a> I’m show you a Python tool called a ‘generator’. Properly used that simplifies tasks like this. If you are just here for fast solutions, here is a <a href="https://gist.github.com/glantonb/114bc8fec08bddf1671b33817e9c2e23#file-euler2_gist_sol-py">gist</a>.</blockquote><p>The gotcha to discover when writing a solution to Fibonacci is that the calculation is recursive. Any naive solution is repetitive, and quickly gets bigger than your computer.</p><p>The problem pops up because each Fibonacci number is that it’s defined as</p><blockquote>nth = (n-1)th + (n-2)th</blockquote><p>where the<em> (n-1)</em>th is defined as</p><blockquote>(n-1)th = (n-2)th + (n-3)th</blockquote><p>So really</p><blockquote>nth = (n-2)th + (n-3)th + (n-2)th</blockquote><p>Repetition of calculating fib(n-2) twice is the tip of an iceberg of arithmetic. Every time we get calculate a later term in Fibonacci we have more additions steps than we did in any of the earlier steps. For this problem we’re doing 4 million terms!</p><p>You may already be thinking that a smart developer would think for a bit and design a solution that counted upwards, and stored only a few numbers. Shouldn’t take you much longer to design that than it will take to read this article.</p><p>Oooor, you could read the manual. It is friendly.</p><h3>The Least Thinking Solution Possible</h3><p>Python has extensive docs,written by and for programmers. The <a href="https://docs.python.org/3/library/functools.html#functools.lru_cache">docs</a> for a thing called an ‘LRU Cache’ are a gem. They use Fibonacci as one of <em>their </em>examples:</p><p>Gist 1 — Naive Fibonacci</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6c98e94aed9995d636f10c4884fa3da/href">https://medium.com/media/a6c98e94aed9995d636f10c4884fa3da/href</a></iframe><p>That looks a lot like what the question requires: code that adds up the two previous terms to generate the next. Any fresh converts to Python just learned that `def` is how to define a function, and that it can take arguments in brackets to tell it what to do. It’s cute that that we can use ‘f’ in front of a string to ask Python to format it — any variables included in curly-braces print their values.</p><p>As presented, this is a bad solution. You can try this, and see how often “Calculating fib…” it printed out, but don’t do it for big numbers!</p><p>If we double the size of ’n’ we much more than double the time taken to get an answer.</p><h3>Can a decoration be useful?</h3><p>The useful example in the Python docs looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/932115b8d3f7b6b0dcc8afa9a726f9dd/href">https://medium.com/media/932115b8d3f7b6b0dcc8afa9a726f9dd/href</a></iframe><p>There is a special line before the function definition. Lines with ‘@’ at the start before functions are usually powerful magic in any language . In Python it means <em>lru_cache() </em>is a ‘<em>decorator</em>’ — a function that took<em> fib()</em> and replaced it. Whenever <em>fib()</em> is called the substitute runs instead. Commonly replacements modify values coming in and out, but use-cases can be inventive.</p><h3>Cache In</h3><p>I owe you an explanation of Least Recently Used caches.</p><p>Checking for previously computed results rather than re-calculating is ‘<a href="https://en.wikipedia.org/wiki/Memoization"><em>memoization</em></a>’. Where computation is expensive but repeatable we might cache the results from a particular set of arguments (cache just means ‘store for later retrieval’). ‘LRU’ means that when we need to remove elements from that cache we choose to ‘evict’ the <strong>L</strong>east <strong>R</strong>ecently <strong>U</strong>sed items, because it’s a good guess that recently used items are used more often than older ‘stale’ results.</p><p>So now we know what we’re doing. We’re wrapping a Least Recently Used cache around our function. After<em> fib()</em> is defined we send it to <em>lru_cache()</em>, which provides a substitute. When lru_cache doesn’t already have an answer to hand<em>, </em>it invokes<em> fib()</em>. When the replacement is invoked for the first time for any ’n’ it will call <em>fib()</em>, but for future calls it will often provide already have stored the answer, and cutting out that recalculation makes our Euler solution thousands of times faster.</p><h3>Inherent Dynamism</h3><p>Python does a lot of work to make that happen.</p><p>You don’t need to read any further. Decorators are well implemented and powerful in Python. The last part of this document discusses more about how Python provides them. I don’t think you can ever know too much about a language, so I love learning and figuring this out. Read the next section if you’d like to extend your mental model of Python a little.</p><p>The simplest way to understand why we call some languages ‘dynamic’ is to look at how functions are built and called.In C, which is “close to the metal” a function is turned into instructions for the processor just once, at ‘compile time’. When a language is compiled for a particular type of computer, part of that process is building an binary file which can work with the operating system to load each function into memory. Modern systems will often check for changes to functions after they’ve been loaded — for ‘static’ languages like C or Rust changes to functions are a good indicator that something has gone wrong.</p><p>Python is a ‘dynamic’ language, it has an entirely different approach. There is a compiler, but it is small and simple and always available. It produces instruction for the Python Virtual Machine, and that is the component that makes machine instruction for the processor. The Python Virtual Machine does get loaded like a static C program, a lot of the VM’s are written in C. Everything you write is dynamic — in fact some components write new Python code for you, and add it <em>after your program has started running.</em></p><p>Python can’t provide a static map to functions that don’t exist yet to the processor as it starts. It does know where all the C functions it will use to make your code go will be though. So instead it provides works like a phone book, indexing names of functions to locations in memory where they can be called. Static languages don’t have to do that step, which is why Python is nearly always slower than static languages.</p><p>The take-away is not “write fewer bigger functions, so less look-ups” — because people find functions easier, and programs are for people, not computers. I’d like you to take away the idea that Python is very flexible, and you should think about what’s a natural way to express a good solution and then what tools you have available to implement that. It’s a truly great language to prototype something that looks right. Once you have correct in place you can decide if it you really need it to be faster and start optimising or translating to a static language only if you need to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c2277e42b03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Well Euled Machines — 1]]></title>
            <link>https://medium.com/@glantonb/well-euled-machines-575bdbc195d8?source=rss-bb9a2cd23af3------2</link>
            <guid isPermaLink="false">https://medium.com/p/575bdbc195d8</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[euler]]></category>
            <dc:creator><![CDATA[Ben Glanton]]></dc:creator>
            <pubDate>Wed, 09 Feb 2022 01:34:55 GMT</pubDate>
            <atom:updated>2024-08-07T23:48:47.162Z</atom:updated>
            <content:encoded><![CDATA[<h4>1 of 5 —Together we write the simplest program to be even slightly useful, detailing stuff that will be useful later</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*IQUVINWHwY7r8Ik6JOODbQ.png" /><figcaption>The Python Logo (Two stylized snakes form a + sign. The word ‘python’)</figcaption></figure><p><em>Python </em>is a lovely programming language that aims to produce “executable pseudo-code”. Oriented around developer happiness it has a simple model, backed by a compiler so small the language sometimes compiles new source code for you while running. Python programs are often slow to run, but computers are very fast, so it’s easy to build something quick-enough as an experiment and that often has enormous value.</p><p>The <em>Euler project </em>is an Open Source set of challenges supported by donations. Solving problems unlocks discussion pages and skipping ahead is always allowed. A good solution should run in less than a minute, you’ll generally learn far more when you try to build fast solutions. You can find Project Euler <a href="https://projecteuler.net/">here</a>.</p><p>I think that Euler problems are a really good way to get to know a new programming language, and so do a lot of other people. This series is intended for people who know a programming language already, probably Java, but have decided that now would be a great time to pick up some Python — or to learn more. It seems Python is becoming ‘table stakes’ in the jobs market, but there’s a big difference between writing working code and writing excellent code: communicating effectively <em>always </em>helps, I’d like to help you learn to communicate well.</p><p>Project Euler discourage publishing answers for questions after the first 100. I’m going to respect that, each of the first 5 is a chance to pick up new things.</p><p>Project Euler Problem 1:</p><blockquote><em>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</em></blockquote><blockquote><em>Find the sum of all the multiples of 3 or 5 below 1000.</em></blockquote><p>This is a problem called ‘FizzBuzz’. Project Euler are being nice. FizzBuzz might be second only to ‘print “Hello world!” for being used to learn the basics of a new language. It is also a game for people who think ‘lets become far more drunk’.</p><p>For most developers the natural way to start solving the problem is a for-loop. I encourage you to use a <em>list comprehension </em>instead for two reasons. Comprehension are the natural tool in Python, so it will surprise other developers less. Secondly, and it really is a secondary consideration in this case, a simpler solution is possible. We can get close to saying “this is what the problem is” rather than “these are the steps that I say solved the problem”. That’s good because we should always try to make it easier for a reviewer to understand that you are correct.</p><h4>Comprehensions</h4><p>Python has several types of comprehension. All comprehensions make a collection of things you want out of another collection. You can short-circuit a lot of learning if you remember some set theory (high school level where I come from). The basic form reads most naturally as “for every <em>x</em> in <em>x-source, </em>make me one of these”.</p><p>In Python ‘range()’ is the default way to get a list we can transform into a new form. We tell it where we want to start (default 0) and to end (required), and what step-size we want (default “+1 every step”).</p><h4>Most of a solution — in one line</h4><p>Python comprehensions always work like “I have this collection of things, here’s what I want to do with them”. We want to pick out just the numbers that are divisible by one or both of 3 or 5. We can check that’s working OK in <em>REPL</em>. <strong>R</strong>ead <strong>E</strong>xecute <strong>P</strong>rint <strong>L</strong>oop is what you get if you just enter ‘Python3’ at the command line. We’ll use it to quickly check that your code works the way you expect. In REPL type (or paste):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26603f7abfc93f7c3bc654622599d0dd/href">https://medium.com/media/26603f7abfc93f7c3bc654622599d0dd/href</a></iframe><p>which produces: “[3, 5, 6, 9, 10, …996, 999, 1000]”.</p><p>That certainly looks like the numbers we want. Notice that they are printed in square-brackets, which tell us we’re looking at a list.</p><h4>Breaking it down</h4><p>At the heart of the comprehension we’ve said <strong>x for x in range(1, 1001)</strong>. ‘x’ is just a name I picked to sound ‘mathsy’. <em>Range</em> will set <em>x </em>to every number from 1 to 1000 inclusive. <em>Note that 1001 does not come out of the generator </em>think of it as being a book-end — not a book.</p><p>There’s an <strong>if </strong>clause attached to our comprehension. ‘%’ is the symbol for <em>modulus </em>(or clock arithmetic if you prefer). x % 3 gives us the remainder after x is divided by 3 — remainders are 0 for multiples of 3. Python likes to use words, so building we can say if “only if the remainder is 0 after modulus 3 <strong>or<em> </em></strong>the remainder is 0 after modulus 5, keep the number in the list”. For most people the Python ‘or’ is a lot more readable than the symbolic version like ‘||’ which a lot of language designers use.</p><p>I feel that a list comprehension makes for <em>obvious</em> code in this solution. There’s a rough 1-to-1 match from lines of description in English and lines in Python. It uses the relatively high power of code in Python to write less code, it is always better if you can avoid complexity. Importantly we’ve not really had to tell the computer much about <em>how</em> to build the list of numbers we want, we just said <em>what we want</em>.</p><p>The last thing we need to do is total up the list. Once again, we <em>could </em>write a whole loop to add up all those values in the list. That’s something programmers have to do a lot though. So there is a tool in Python which can do that for us.</p><p>In mathematical terms we want to get the ‘sum’ of that list, so we can wrap a function called ‘sum()’ around the code we’ve already written:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a81061db164d3033cb5b360950d43c8/href">https://medium.com/media/5a81061db164d3033cb5b360950d43c8/href</a></iframe><p>If you run in REPL, or through an IDE you’ll find ProjectEuler.net will accept your answer.</p><p>Well done. Especially if this is the first time you’ve written Python to solve a ‘real’ problem.</p><h4>Take-away</h4><p>Python loops are always like ‘for each of these things’ (which is what C++ and Java prefer too now).<br>There’s a <em>sum()</em> function to add-up lists (and Euler will see you use it a lot).<br>You don’t need to write a whole program in a source file for simple stuff.<br>Python wants you to be happy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=575bdbc195d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>