<?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 William Bresnan on Medium]]></title>
        <description><![CDATA[Stories by William Bresnan on Medium]]></description>
        <link>https://medium.com/@williambengineering?source=rss-bbf6a1d22e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sUIRQEIMPS6oFjGZqw-tJw.jpeg</url>
            <title>Stories by William Bresnan on Medium</title>
            <link>https://medium.com/@williambengineering?source=rss-bbf6a1d22e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:33:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@williambengineering/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[Writing the worst possible ‘isOdd’ function in Python]]></title>
            <link>https://williambengineering.medium.com/writing-the-worst-possible-isodd-function-in-python-7049c0131219?source=rss-bbf6a1d22e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7049c0131219</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[William Bresnan]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 01:22:48 GMT</pubDate>
            <atom:updated>2023-02-25T01:22:48.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*QUZqVtrxnmkj0Sn9g7JZZw.png" /></figure><p>A frequent meme on Reddit’s r/ProgrammerHumor is poorly performing or overly complex isOdd/isEven implementations. Having nothing more important to be doing with my afternoon, I decided to give it a shot and see what I could come up with. Of course, we can’t just submit bad code and say it’s bad, we need to test it and collect data on how it performs. To this end, I’ve come up with a number of implementations and we’ll go through them one at a time and see just how funky we can make it.</p><p>There are a few ground rules I set for these implementations:</p><ol><li>It must return the correct answer</li><li>No useless operations e.g. encrypting and decrypting the number 100 times to pad the time</li><li>No stack overflows, infinite loops, or impossible solutions ala <a href="http://wiki.c2.com/?QuantumBogoSort">Quantum Bogosort</a></li></ol><p>That out of the way, let us take a look at our first implementation and go over the testing protocol.</p><h3><strong>The Testing Methodology</strong></h3><p>We measure our elapsed time using Python’s built-in timeit module.</p><pre>import timeit<br><br>starttime = timeit.default_timer()<br>result = is_odd(number)<br>endtime = timeit.default_timer() - starttime</pre><p>We’ll run 10,000 tests if possible and average out the runtime. Some implementations won’t be able to do 10,000 tests for reasons we’ll get into when we get there.</p><h3><strong>The Base Case</strong></h3><p>We can’t go through our bad solutions before first testing the simple and easy solution.</p><pre>def is_odd(number):<br>    return number % 2 == 1</pre><p>Yep, that’s the implementation we all know and here’s how it performed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*NZDIMzxQ6cTXdOnrn7FZdQ.png" /></figure><p>Pretty quick. But I think there’s room for retrogression.</p><h3><strong>Incrementor and Decrementor</strong></h3><p>I’ve grouped these two together as they both rely on ‘while’ loops to adjust the tested value until it reaches a certain point</p><pre>def is_odd(number):<br>    incrementor = 1<br>    is_incrementor_odd = True<br>    while incrementor &lt; number:<br>        incrementor += 1<br>        if is_incrementor_odd:<br>            is_incrementor_odd = False<br>        else:<br>            is_incrementor_odd = True<br><br>    return is_incrementor_odd</pre><p>In this one, we start off with the assumption that 1 is, in fact, odd. Then, we increment by 1 over and over, flipping our boolean flag each time until we reach the input number, then return our stored boolean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*QADQLcQM_sWgF5d0zXUfWg.png" /></figure><p>That was the incrementor implementation, and now we’ll look at the reduction implementation.</p><pre>def is_odd(number):<br><br>    while number &gt; 1:<br>        number -= 2<br><br>    if number == 1:<br>        return True<br>    else:<br>        return False</pre><p>In this one, we reduce our inputted value by 2 repeatedly, until it’s less than or equal to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*er-7Hq5a0dMYALHSQSbuvQ.png" /></figure><p>Of course, for both of these implementations the performance suffers more and more the larger the number is. We’re moving in the right and/or wrong direction, but we can do worse and/or better.</p><h3><strong>Binary String</strong></h3><p>In binary, if the least significant bit is 1, then we’ll know it’s an odd number.</p><pre>def is_odd(number):<br>    binary_number = bin(number)<br>    lsb = binary_number[-1]<br><br>    return lsb == &quot;1&quot;</pre><p>As it turns out, the conversion to a binary string and grabbing the last digit is unfortunately very quick, and showed only a minimal hit to performance relative to our base case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*XJjRoS-wbCaKu7O6poBDdQ.png" /></figure><h3><strong>World’s Longest Conditional Statement</strong></h3><p>Just how long can you make a conditional statement in Python?</p><pre>def is_odd(number):<br>    if number == 1 or number == 3 or number == 5 or number == 7 or.........:<br>        return True<br>   <br>    return False</pre><p>Turns out it’s around 3450 conditionals in a single ‘if’ statement before the Python interpreter goes “WTF ARE YOU DOING?” and fails to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*ggD67WefRUa-YuVh6Jb_Vw.png" /></figure><p>Despite how long our conditional is, it’s still pretty quick. Unfortunately, a mere 3450 conditions is only enough to handle integers up to 6900, so we’re going to need a more scalable solution.</p><h3><strong>File Read</strong></h3><p>Why waste valuable runtime doing <em>math</em> to figure out whether a number is odd when we could simply pre-compute every odd number for later reference?</p><pre>def is_odd(number):<br>    odd_file = open(&#39;odd_numbers&#39;, &#39;r&#39;)<br>    lines = odd_file.readlines()<br><br>    for line in lines:<br>        if str(number) == line.rstrip(&#39;\n&#39;):<br>            return True<br><br>    return False</pre><p>We have a file running along side our application containing every odd number in existence. When we want to determine oddness, we open our file and check to see if it’s there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*DStyfsxdCGU05oqStThTmQ.png" /></figure><p>This implementation suffers from poor performance the larger the number. When passed an even number, we must parse the entire odd reference file before we can determine that it is even, which makes the performance on average even worse.</p><h3><strong>The Interpreter</strong></h3><p>Credit to u/evinrows for this one. They found that you can pass empty parenthesis into the python interpreter and it’ll evaluate it without issue, assuming the parenthesis are balanced.</p><pre>def is_odd(number):<br>    # credit to u/evinrows<br>    try:<br>        exec(&#39;(&#39; * len(range(number)[:math.floor(((number + 1)/2))]) + len(range(number)[math.floor(((number + 1)/2)):]) * &#39;)&#39;)<br>        return False<br>    except Exception as e:<br>        return True</pre><p>We create a string of (N + 1) / 2 left parenthesis, and (N+1) / 2 right parenthesis, and try to exec it with the python interpreter. If the left and right are balanced, the interpreter will exec this and exit with code 0. If they’re not balanced, it’ll throw an error and then we know we have an odd number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*t_pRjAR-dHa4JQb6OdsjuA.png" /></figure><p>It’s surprisingly fast, though it does have a major limitation; we can only test integers up to 99 since the interpreter can’t handle 100 or more nested pairs of parenthesis.</p><h3><strong>Palindrome</strong></h3><p>Though it looks like it might be at first glance</p><p>)()()(</p><p>is actually not a palindrome however</p><p>)()()()</p><p><em>is</em> a palindrome. I wondered if we could use this concept of palindromes to check if a number is odd.</p><pre>def is_odd(number):<br>    def is_palindrome(s):<br>        return s == s[::-1]<br><br>    if number == 1:<br>        return True<br><br>    string = &#39;&#39;<br>    last_was_left_par = False<br>    for x in range(1, number + 1):<br>        if last_was_left_par:<br>            string += &#39;(&#39;<br>            last_was_left_par = False<br>        else:<br>            last_was_left_par = True<br>            string += &#39;)&#39;<br><br>    return is_palindrome(string)</pre><p>We construct a string of alternating parentheses, then check if it’s a palindrome. If it’s not a palindrome, we know it’s even, but if it is a palindrome, then we know it’s odd.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*PGs5K5nXt7XFVfyTRfJfFA.png" /></figure><h3><strong>ChatGPT’s Submission</strong></h3><p>As 2022 and 2023’s most exciting new “celebrity”, I thought I’d ask to see what ChatCPT could come up with.</p><pre>def is_odd(n):<br>    # Convert the integer to a list of digits<br>    digits = [int(d) for d in str(n)]<br><br>    # Compute the sum of the squares of the digits<br>    sum_of_squares = sum([d**2 for d in digits])<br><br>    # Compute the sum of the squares of the prime factors of the sum of the squares<br>    prime_factors = []<br>    for i in range(2, sum_of_squares):<br>        if sum_of_squares % i == 0:<br>            is_prime = True<br>            for j in range(2, int(i**0.5)+1):<br>                if i % j == 0:<br>                    is_prime = False<br>                    break<br>            if is_prime:<br>                prime_factors.append(i)<br>    prime_factor_squares = [p**2 for p in prime_factors]<br>    sum_of_factor_squares = sum(prime_factor_squares)<br><br>    # Compute the number of non-zero digits in the binary representation of the sum of the factor squares<br>    binary_digits = [int(d) for d in bin(sum_of_factor_squares)[2:]]<br>    num_nonzero_digits = sum([1 for d in binary_digits if d == 1])<br><br>    # Determine if the number of non-zero digits is odd<br>    return num_nonzero_digits % 2 == 1</pre><pre>def is_odd(n):<br>    s = str(n)<br>    l = len(s)<br>    if l &gt; 1:<br>        first_digit = int(s[0])<br>        if first_digit in [1, 3, 5, 7, 9]:<br>            return True<br>        elif first_digit == 2:<br>            if l &gt; 2:<br>                second_digit = int(s[1])<br>                if second_digit in [1, 3, 5, 7, 9]:<br>                    return True<br>                else:<br>                    third_digit = int(s[2])<br>                    if third_digit in [1, 3, 5, 7, 9]:<br>                        return True<br>        elif first_digit == 4:<br>            if l &gt; 2:<br>                second_digit = int(s[1])<br>                if second_digit in [1, 3, 5, 7, 9]:<br>                    return True<br>                else:<br>                    third_digit = int(s[2])<br>                    if third_digit in [1, 3, 5, 7, 9]:<br>                        return True<br>        elif first_digit == 6:<br>            if l &gt; 2:<br>                second_digit = int(s[1])<br>                if second_digit in [1, 3, 5, 7, 9]:<br>                    return True<br>                else:<br>                    third_digit = int(s[2])<br>                    if third_digit in [1, 3, 5, 7, 9]:<br>                        return True<br>        elif first_digit == 8:<br>            if l &gt; 2:<br>                second_digit = int(s[1])<br>                if second_digit in [1, 3, 5, 7, 9]:<br>                    return True<br>                else:<br>                    third_digit = int(s[2])<br>                    if third_digit in [1, 3, 5, 7, 9]:<br>                        return True<br>    elif l == 1:<br>        if n == 1 or n == 3 or n == 5 or n == 7 or n == 9:<br>            return True<br>    return False</pre><pre>def is_odd(number):<br>    start = time.time()<br>    x = 0<br>    for i in range(2, number):<br>        x += i % 2<br>        time.sleep(0.01)<br>    print(f&quot;Execution time: {time.time() - start:.2f} seconds&quot;)<br>    return bool(x % 2)</pre><p>Unfortunately, all of these solutions violate my rules either by returning incorrect answers or engaging in useless operations. Oh well, it looks like it’s not putting me out of a job just yet.</p><h3><strong>Microservices</strong></h3><p>What are we going to do when our hot new application gets VC funding and really starts taking off? With microservices, we can break down our entire system into tiny, bite-sized pieces that are just so much easier to manage. Who needs cohesive software architecture when you can have a patchwork quilt of services that communicate through an impenetrable web of APIs? We’re definitely going to need to handle millions of requests per second any day now, so we better implement a microservice to handle the vast quantity of odd number checks we’ll be doing.</p><pre>def is_odd(number):<br>    api_url = &quot;https://************/isodd/&quot; + str(number)<br>    response = requests.get(api_url)<br>    response_json = response.json()<br><br>    return response_json.get(&#39;isOdd&#39;)</pre><p>I wrote some server code, set up some routes, deployed it using <a href="https://fly.io/">Fly.io</a>, and then hit it with requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*7RKJlaXMk20t-tiq6hW3xg.png" /></figure><p>It’s definitely not fast since it’s subject to network latency, and it’s certainly not simple, but at least it can scale alongside our business needs. Right? Right?</p><h3><strong>Conclusion</strong></h3><p>So, uhh, what did we learn here? Well, not much, but it was kind of a fun exercise. Though this article is fairly useless, and mostly serves as a s**tpost, I do have some more interesting ideas for future content. I figured if nothing else this will help me get back into the habit of writing again. Look forward to that coming soon. Thanks for reading, and be kind to one another.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7049c0131219" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>