Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python One Line FizzBuzz

#1
Python One Line FizzBuzz

<div><p>The <a href="https://en.wikipedia.org/wiki/Fizz_buzz" target="_blank" rel="noreferrer noopener">FizzBuzz </a>problem is a common exercise posed in code interviews to test your proficiency in writing simple Python code.</p>
<p><strong>Problem</strong>: Print all numbers from 1-100 to the shell with three exceptions: </p>
<ul>
<li>For each number divisible by three you print <code>"Fizz"</code>, </li>
<li>For each number divisible by five you print <code>"Buzz"</code>, and</li>
<li>For each number divisible by three and five you print <code>"FizzBuzz"</code>. </li>
</ul>
<p><strong>Example</strong>: The first 15 numbers of the FizzBuzz sequence are the following.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
...</pre>
<p>How to write a <a href="https://blog.finxter.com/python-one-line-x/" target="_blank" rel="noreferrer noopener" title="Python One Line X">Python one-liner</a> that solves this problem?</p>
<p>Here’s an interactive overview:</p>
<p> <iframe src="https://repl.it/@finxter/RashMintyConstants?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="600px" frameborder="no"></iframe> </p>
<p><em><strong>Exercise</strong>: Do both one-liners produce the same results? Run the code to check!</em></p>
<p>Let’s dive into those one-liners to gain a deeper understanding and improve your Python skills!</p>
<h2>FizzBuzz One-Liner 1: Generator Expression + String Concatenation + Short Circuiting</h2>
<p>The following one-liner solves the problem in an elegant way using a fine understanding of more advanced Python features (<a href="http://michaeljgilliland.blogspot.com/2013/01/one-line-fizz-buzz-test-in-python.html" target="_blank" rel="noreferrer noopener" title="http://michaeljgilliland.blogspot.com/2013/01/one-line-fizz-buzz-test-in-python.html">source</a>). </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print('\n'.join('Fizz' * (i%3==0) + 'Buzz' * (i%5==0) or str(i) for i in range(1,101)))</pre>
<p>The one-liner creates a string using the <code><a href="https://blog.finxter.com/python-join-list/" title="Python Join List [Ultimate Guide]" target="_blank" rel="noreferrer noopener">join</a></code> function with the newline character as a delimiter. Here’s a short explanation of the function:</p>
<p class="has-pale-cyan-blue-background-color has-background">The <code>string.join(iterable)</code> method concatenates all the string elements in the <code>iterable</code> (such as a list, string, or tuple) and returns the result as a new string. The <code>string</code> on which you call it is the delimiter string—and it separates the individual elements. For example, <code>'-'.join(['hello', 'world'])</code> returns the joined string <code>'hello-world'</code>.</p>
<p>So, what’s the iterable, you pass into the <code>join()</code> function? It’s a generator expression of the form: <code>expression for variable in context</code>. You go over all integer values in the context 1 to 100 using the <code><a href="https://blog.finxter.com/python-join-list-range-a-helpful-guide/" title="Python Join List Range: A Helpful Guide" target="_blank" rel="noreferrer noopener">range()</a></code> function. So, you obtain the remaining <code>expression for i in range(1, 101)</code>. What’s the expression part?</p>
<p>It consists of three elements: </p>
<ul>
<li><code>'Fizz' * (i%3==0)</code> — The <a href="https://en.wikipedia.org/wiki/Modulo_operation" target="_blank" rel="noreferrer noopener" title="https://en.wikipedia.org/wiki/Modulo_operation">modulo </a>expression <code>i%3==0</code> returns <code>True</code> only if the integer <code>i</code> is divisible by 3, otherwise it returns <code>False</code>. So, you multiply the string <code>'Fizz'</code> either with <code>True</code> (=1) or with <code>False</code> (=0). As a result, you obtain the empty string <code>''</code> in all cases except if the integer <code>i</code> is divisible by 3—in which case you obtain the string <code>'Fizz'</code>. </li>
<li><code>'Buzz' * (i%5==0)</code>— The <a href="https://en.wikipedia.org/wiki/Modulo_operation" target="_blank" rel="noreferrer noopener">modulo </a>expression <code>i%5==0</code> returns <code>True</code> only if the integer <code>i</code> is divisible by 5, otherwise it returns <code>False</code>. So, you multiply the string <code>'Buzz'</code> either with <code>True</code> (=1) or with <code>False</code> (=0). As a result, you obtain the empty string <code>''</code> in all cases except if the integer <code>i</code> is divisible by 5—in which case you obtain the string <code>'Buzz'</code>.</li>
<li>You use string concatenation to glue together the previously obtained strings. In most cases, this will be the empty string. If <code>i</code> is divisible by 3, you obtain the string <code>'Fizz'</code>. If <code>i</code> is divisible by 5, you obtain the string <code>'Buzz'</code>. And if <code>i</code> is divisible by 3 and 5, you obtain the string <code>'FizzBuzz'</code>. </li>
<li><code>or str(i)</code> — In the case you obtained a non-empty string in <code>{'Fizz', 'Buzz', 'FizzBuzz'}</code> in the previous step, the <code><a href="https://blog.finxter.com/python-one-line-and-or/" title="Python One Line And/Or" target="_blank" rel="noreferrer noopener">or</a></code> operation simply returns this string. This is called <a href="https://blog.finxter.com/what-is-short-circuit-evaluation-in-python/" title="What is Short Circuit Evaluation in Python?" target="_blank" rel="noreferrer noopener">short circuiting</a>—and it’s used in many programming languages such as Python to improve efficiency of logical operations. </li>
<li>But if the string is empty, it is interpreted as a logical <code>False</code>. Thus, Python returns the second operand of the <code>or</code> operation. The second operand simply is the string representation of the integer <code>i</code>. </li>
</ul>
<p>A very interesting implementation of the FizzBuzz problem indeed!</p>
<h2>FizzBuzz One-Liner 2: Slicing</h2>
<p>An alternative is given in the following nice one-liner (source):</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">for i in range(1, 101): print('FizzBuzz'[i*i%3*4:8--i**4%5] or i)</pre>
<p>Wow—what a short and concise one-liner solution! But how does it work?</p>
<ul>
<li>You iterate over all values from <code>i=1</code> to <code>i=100</code> and print a string. So far so good. </li>
<li>You use the <code>or</code> operation and slicing to determine the string <code>'FizzBuzz'[start:end] or i</code> generates the output. </li>
<li>You use the property of short circuiting in Python: If <code>'FizzBuzz'[start:end]</code> is empty, the integer <code>i</code> is returned, otherwise, the non-empty string is returned.</li>
<li>You carve out a substring from <code>'FizzBuzz'</code> using <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" target="_blank" rel="noreferrer noopener" title="Introduction to Slicing in Python">slicing </a>as follows.</li>
</ul>
<p>Slicing is a concept to carve out a substring from a given string. Use slicing notation <code>s[start:stop:step]</code> to access every <code>step</code>-th element starting from index <code>start</code> (included) and ending in index <code>stop</code> (excluded). All three arguments are optional, so you can skip them to use the default values (<code>start=0</code>, <code>stop=len(lst)</code>, <code>step=1</code>). For example, the expression <code>s[2:4]</code> from string <code>'hello'</code> carves out the slice <code>'ll'</code> and the expression <code>s[:3:2]</code> carves out the slice <code>'hl'</code>.</p>
<p>In the example, you have the slicing operation <code>'FizzBuzz'[i*i%3*4:8--i**4%5]</code>. </p>
<ul>
<li><code>start = i*i%3*4</code> — Note that the multiplication <code>*</code> and modulo operation <code>%</code> have the same priority, so they are evaluated from left to right. If integer <code>i</code> is divisible by 3, <code>i*i</code> is also divisible by 3, and the start index is 0. In all other cases, the start index is 4. Thus, the slice either starts with <code>'Fizz'</code> or <code>'Buzz'</code>. </li>
<li><code>stop = 8--i**4%5</code> — This is 4 in all cases except if the number <code>i</code> is divisible by 5, in which case this is 8. </li>
</ul>
<p>So, there are four cases:</p>
<ul>
<li>The number is divisible only by 3: <code>start=0</code>, <code>stop=4</code> –&gt; <code>'Fizz'</code></li>
<li>The number is divisible only by 5: <code>start=4</code>, <code>stop=8</code> –&gt; <code>'Buzz'</code></li>
<li>The number is divisible by both 3 and 5: <code>start=0</code>, <code>stop=8</code> –&gt; <code>'FizzBuzz'</code></li>
<li>The number is divisible by neither 3 nor 5: <code>start = 4</code>, <code>stop=4</code> –&gt; <code>''</code></li>
</ul>
<p>Phew! This was a hard nut to crack, wasn’t it?</p>
<h2>Python One-Liner 3: Map + Lambda</h2>
<p>You can find detailed tutorials on the map and lambda functions here:</p>
<ul>
<li><a href="https://blog.finxter.com/daily-python-puzzle-string-encrpytion-ord-function-map-function/" title="Mastering the Python Map Function [+Video]" target="_blank" rel="noreferrer noopener"><a href="https://blog.finxter.com/daily-python-puzzle-string-encrpytion-ord-function-map-function/" target="_blank" rel="noreferrer noopener">Mastering the Python Map Function</a></a></li>
<li><a href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" title="Lambda Functions in Python: A Simple Introduction" target="_blank" rel="noreferrer noopener"><a href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank" rel="noreferrer noopener">Lambda Functions in Python</a></a></li>
</ul>
<p>Those two functions can be used to solve the FizzBuzz problem (<a href="https://gist.github.com/konstantinfarrell/c4f84ea579615da63de0eb325753b71d" target="_blank" rel="noreferrer noopener" title="https://gist.github.com/konstantinfarrell/c4f84ea579615da63de0eb325753b71d">source</a>):</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">print(list(map(lambda i: "Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i), range(1,101))))</pre>
<p>It’s similar to Method 1 and by now you’re able to figure it out. Think of the different values the integer <code>i</code> can take. </p>
<h2>Python One-Liners Book</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<figure class="wp-block-image size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
<p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Python One-Liners</em> </a>will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:</p>
<p><strong>•</strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br /><strong>•</strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br /><strong>•</strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br /><strong>•</strong>&nbsp;&nbsp;Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators<br /><strong>•</strong>&nbsp;&nbsp;Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting</p>
<p>By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners Now!!</em></a></strong></p>
</div>


https://www.sickgaming.net/blog/2020/09/...-fizzbuzz/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016