{"id":117617,"date":"2020-09-06T07:43:29","date_gmt":"2020-09-06T07:43:29","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=12756"},"modified":"2020-09-06T07:43:29","modified_gmt":"2020-09-06T07:43:29","slug":"python-one-line-fizzbuzz","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/09\/06\/python-one-line-fizzbuzz\/","title":{"rendered":"Python One Line FizzBuzz"},"content":{"rendered":"<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>\n<p><strong>Problem<\/strong>: Print all numbers from 1-100 to the shell with three exceptions: <\/p>\n<ul>\n<li>For each number divisible by three you print <code>\"Fizz\"<\/code>, <\/li>\n<li>For each number divisible by five you print <code>\"Buzz\"<\/code>, and<\/li>\n<li>For each number divisible by three and five you print <code>\"FizzBuzz\"<\/code>. <\/li>\n<\/ul>\n<p><strong>Example<\/strong>: The first 15 numbers of the FizzBuzz sequence are the following.<\/p>\n<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\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n...<\/pre>\n<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>\n<p>Here&#8217;s an interactive overview:<\/p>\n<p> <iframe loading=\"lazy\" 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>\n<p><em><strong>Exercise<\/strong>: Do both one-liners produce the same results? Run the code to check!<\/em><\/p>\n<p>Let&#8217;s dive into those one-liners to gain a deeper understanding and improve your Python skills!<\/p>\n<h2>FizzBuzz One-Liner 1: Generator Expression + String Concatenation + Short Circuiting<\/h2>\n<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>\n<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>\n<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&#8217;s a short explanation of the function:<\/p>\n<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\u2014and it separates the individual elements. For example, <code>'-'.join(['hello', 'world'])<\/code> returns the joined string <code>'hello-world'<\/code>.<\/p>\n<p>So, what&#8217;s the iterable, you pass into the <code>join()<\/code> function? It&#8217;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&#8217;s the expression part?<\/p>\n<p>It consists of three elements: <\/p>\n<ul>\n<li><code>'Fizz' * (i%3==0)<\/code> &#8212; 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&#8212;in which case you obtain the string <code>'Fizz'<\/code>. <\/li>\n<li><code>'Buzz' * (i%5==0)<\/code>&#8212; 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&#8212;in which case you obtain the string <code>'Buzz'<\/code>.<\/li>\n<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>\n<li><code>or str(i)<\/code> &#8212; 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>&#8212;and it&#8217;s used in many programming languages such as Python to improve efficiency of logical operations. <\/li>\n<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>\n<\/ul>\n<p>A very interesting implementation of the FizzBuzz problem indeed!<\/p>\n<h2>FizzBuzz One-Liner 2: Slicing<\/h2>\n<p>An alternative is given in the following nice one-liner (source):<\/p>\n<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>\n<p>Wow&#8212;what a short and concise one-liner solution! But how does it work?<\/p>\n<ul>\n<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>\n<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>\n<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>\n<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>\n<\/ul>\n<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>\n<p>In the example, you have the slicing operation <code>'FizzBuzz'[i*i%3*4:8--i**4%5]<\/code>. <\/p>\n<ul>\n<li><code>start = i*i%3*4<\/code> &#8212; 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>\n<li><code>stop = 8--i**4%5<\/code> &#8212; This is 4 in all cases except if the number <code>i<\/code> is divisible by 5, in which case this is 8. <\/li>\n<\/ul>\n<p>So, there are four cases:<\/p>\n<ul>\n<li>The number is divisible only by 3: <code>start=0<\/code>, <code>stop=4<\/code> &#8211;&gt; <code>'Fizz'<\/code><\/li>\n<li>The number is divisible only by 5: <code>start=4<\/code>, <code>stop=8<\/code> &#8211;&gt; <code>'Buzz'<\/code><\/li>\n<li>The number is divisible by both 3 and 5: <code>start=0<\/code>, <code>stop=8<\/code> &#8211;&gt; <code>'FizzBuzz'<\/code><\/li>\n<li>The number is divisible by neither 3 nor 5: <code>start = 4<\/code>, <code>stop=4<\/code> &#8211;&gt; <code>''<\/code><\/li>\n<\/ul>\n<p>Phew! This was a hard nut to crack, wasn&#8217;t it?<\/p>\n<h2>Python One-Liner 3: Map + Lambda<\/h2>\n<p>You can find detailed tutorials on the map and lambda functions here:<\/p>\n<ul>\n<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>\n<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>\n<\/ul>\n<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>\n<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>\n<p>It&#8217;s similar to Method 1 and by now you&#8217;re able to figure it out. Think of the different values the integer <code>i<\/code> can take. <\/p>\n<h2>Python One-Liners Book<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<figure class=\"wp-block-image size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" 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\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<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 &#8220;one-liners&#8221;: concise statements of useful functionality packed into a single line of code. You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;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&#8217;ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You&#8217;ll also learn how to:<\/p>\n<p><strong>\u2022<\/strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br \/><strong>\u2022<\/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>\u2022<\/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>\n<p>By the end of the book, you&#8217;ll know how to write Python at its most refined, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<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>\n","protected":false},"excerpt":{"rendered":"<p>The FizzBuzz problem is a common exercise posed in code interviews to test your proficiency in writing simple Python code. Problem: Print all numbers from 1-100 to the shell with three exceptions: For each number divisible by three you print &#8220;Fizz&#8221;, For each number divisible by five you print &#8220;Buzz&#8221;, and For each number divisible [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-117617","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/117617","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=117617"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/117617\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=117617"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=117617"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=117617"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}