[Tut] Python One Line X - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Python One Line X (/thread-96162.html) |
[Tut] Python One Line X - xSicKxBot - 07-13-2020 Python One Line X <div><p>This is a running document in which I’ll answer all questions regarding the single line of Python code. If you want to check out my book <a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noreferrer noopener" title="https://www.amazon.com/gp/product/B07ZY7XMX8">“Python One-Liners”</a> and <strong>become a one-liner wizard</strong>—be my guest! <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f609.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p> <p>Let’s get started!</p> <h2>Python One Line If Without Else</h2> <h2>Python One Line If Else</h2> <h2>Python One Line Elif</h2> <h2>Python One Line Function</h2> <h2>Python One Line For Loop</h2> <h2>Python One Line For Loop If</h2> <h2>Python One Line For Loop Lambda</h2> <h2>Python One Line While Loop</h2> <h2>Python One Line HTTP Web Server</h2> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <div class="ast-oembed-container"><iframe title="The Top 18 Best Python Tricks" width="1400" height="788" src="https://www.youtube.com/embed/a9nmyrek3qk?start=737&feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </div> </figure> <p>Want to create your own webserver in a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-one-liners-the-ultimate-collection/" target="_blank">single line of Python code</a>? No problem, just use this command in your shell:</p> <figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/image-61.png" alt="" class="wp-image-8636" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/image-61.png 743w, https://blog.finxter.com/wp-content/uploads/2020/05/image-61-300x124.png 300w" sizes="(max-width: 743px) 100vw, 743px" /></figure> <pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ python -m http.server 8000</pre> <p>The terminal will tell you:</p> <pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Serving HTTP on 0.0.0.0 port 8000</pre> <p>To shut down your webserver, kill the Python program with <code>CTRL+c</code>.</p> <p>This works if you’ve <strong>Python 3</strong> installed on your system. To check your version, use the command <code><a href="https://blog.finxter.com/how-to-check-your-python-version/">python --version</a></code> in your shell. </p> <p><em>You can run this command in your Windows Powershell, Win Command Line, MacOS Terminal, or Linux Bash Script.</em></p> <p>You can see in the screenshot that the server runs on your local host listening on port 8000 (the standard HTTP port to serve web requests).</p> <p><em><strong>Note</strong>: The IP address is <strong>NOT</strong> 0.0.0.0—this is an often-confused mistake by many readers. Instead, your webserver listens at your “local” IP address 127.0.0.1 on port 8000. Thus, only web requests issued on your computer will arrive at this port. The webserver is NOT visible to the outside world.</em></p> <p><strong>Python 2</strong>: To run the same simple webserver on Python 2, you need to use another command using <a href="https://docs.python.org/2/library/simplehttpserver.html" target="_blank" rel="noreferrer noopener"><code>SimpleHTTPServer</code> </a>instead of <code>http</code>:</p> <pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ python -m SimpleHTTPServer 8000 Serving HTTP on 0.0.0.0 port 8000 ...</pre> <p>If you want to start your webserver from within your Python script, no problem:</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="">import http.server import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) httpd.serve_forever()</pre> <p>You can execute this in our online Python browser (yes, you’re creating a local webserver in the browser—how cool is that)!</p> <figure><iframe src="https://repl.it/@finxter/webserver?lite=true" allowfullscreen="true" width="100%" height="1000px"></iframe></figure> <p>This code comes from the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/http.server.html" target="_blank">official Python documentation</a>—feel free to read more if you’re interested in setting up the server (most of the code is relatively self-explanatory). </p> <p><strong>Source</strong>: <a href="https://blog.finxter.com/python-one-liner-webserver/" target="_blank" rel="noreferrer noopener" title="Python One-Liner Webserver HTTP">Python One-Liner Webserver HTTP</a></p> <h2>Python One Line Webshell</h2> <h2>Python One Line Write String to File</h2> <h2>Python One Line Quine</h2> <h2>Python One Line Quicksort</h2> <p>In this one-liner tutorial, you’ll learn about the popular sorting algorithm <a href="https://en.wikipedia.org/wiki/Quicksort">Quicksort</a>. Surprisingly, a single line of Python code is all you need to write the Quicksort algorithm!</p> <p><strong>Problem</strong>: Given a list of numerical values (integer or float). Sort the list in a single line of Python code using the popular <a href="https://blog.finxter.com/python-one-line-quicksort/" target="_blank" rel="noreferrer noopener" title="Python One Line Quicksort">Quicksort </a>algorithm!</p> <p><strong>Example</strong>: You have list <code>[4, 2, 1, 42, 3]</code>. You want to sort the list in ascending order to obtain the new list <code>[1, 2, 3, 4, 42]</code>. </p> <p><strong>Short answer</strong>: The following one-liner solution sorts the list recursively using the Quicksort algorithm: </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="">q = lambda l: q([x for x in l[1:] if x <= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else []</pre> <p>You can try it yourself using the following interactive code shell:</p> <p> <iframe src="https://trinket.io/embed/python/82f77b2571" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p> <p>Now, let’s dive into some details!</p> <p>The following introduction is based on my new book <a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noreferrer noopener" title="https://www.amazon.com/gp/product/B07ZY7XMX8"><strong>“Python One-Liners”</strong></a> <em>(Amazon Link)</em> that teaches you the power of the single line of code (use it wisely)!</p> <figure class="wp-block-image size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="256" height="236" 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="(max-width: 256px) 100vw, 256px" /></a></figure> <p><strong>Introduction</strong>: <a href="https://blog.finxter.com/the-quicksort-algorithm-in-one-line-python/" title="The Shortest Quicksort Implementation in Python" target="_blank" rel="noreferrer noopener">Quicksort </a>is not only a popular question in many <a href="https://blog.finxter.com/python-interview-questions/" title="They Use These 15+ Python Interview Questions To Fail You … (And What You Can Do About It)" target="_blank" rel="noreferrer noopener">code interviews</a> – asked by Google, Facebook, and Amazon – but also a practical <a href="https://blog.finxter.com/python-list-sort/" title="Python List sort() – The Ultimate Guide" target="_blank" rel="noreferrer noopener">sorting </a>algorithm that is fast, concise, and readable. Because of its beauty, you won’t find many introduction to algorithm classes which don’t discuss the Quicksort algorithm.</p> <p><strong>Overview</strong>: Quicksort sorts a list by <a href="https://blog.finxter.com/recursion/" title="Recursion: A Helpful Guide in Python" target="_blank" rel="noreferrer noopener">recursively </a>dividing the big problem (sorting the list) into smaller problems (sorting two smaller lists) and combining the solutions from the smaller problems in a way that it solves the big problem. In order to solve each smaller problem, the same strategy is used recursively: the smaller problems are divided into even smaller subproblems, solved separately, and combined. Because of this strategy, Quicksort belongs to the class of “Divide and Conquer” algorithms.</p> <p><strong>Algorithm</strong>: The main idea of Quicksort is to select a pivot element and then placing all elements that are larger or equal than the pivot element to the right and all elements that are smaller than the pivot element to the left. Now, you have divided the big problem of sorting the list into two smaller subproblems: sorting the right and the left partition of the list. What you do now is to repeat this procedure recursively until you obtain a list with zero elements. This list is already sorted, so the recursion terminates. </p> <p>The following Figure shows the Quicksort algorithm in action:</p> <figure class="wp-block-image"><img src="https://blog.finxter.com/wp-content/uploads/2019/06/image-11.png" alt="" class="wp-image-3689" srcset="https://blog.finxter.com/wp-content/uploads/2019/06/image-11.png 604w, https://blog.finxter.com/wp-content/uploads/2019/06/image-11-300x169.png 300w, https://blog.finxter.com/wp-content/uploads/2019/06/image-11-100x56.png 100w" sizes="(max-width: 604px) 100vw, 604px" /></figure> <p><strong>Figure</strong>: The Quicksort algorithm selects a pivot element, splits up the list into (i) an unsorted sublist with all elements that are smaller or equal than the pivot, and (ii) an unsorted sublist with all elements that are larger than the pivot. Next, the Quicksort algorithm is called recursively on the two unsorted sublists to sort them. As soon as the sublists contain maximally one element, they are sorted by definition – the recursion ends. At every recursion level, the three sublists (left, pivot, right) are concatenated before the resulting list is handed to the higher recursion level.</p> <p><em>You create a function <code>q</code> which implements the Quicksort algorithm in a single line of Python code – and thus sorts any argument given as a list of integers.</em></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="">## The Data unsorted = [33, 2, 3, 45, 6, 54, 33] ## The One-Liner q = lambda l: q([x for x in l[1:] if x <= l[0]]) + [l[0]] + q([x for x in l if x > l[0]]) if l else [] ## The Result print(q(unsorted))</pre> <p>What is the output of this code?</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="">## The Result print(q(unsorted)) # [2, 3, 6, 33, 33, 45, 54]</pre> <h2>Python One Line With Statement</h2> <h2>Python One Line Exception Handling</h2> <h2>Python One Line Try Except</h2> <h2>Python One Line Execute</h2> <h2>Python One Line Reverse Shell</h2> <h2>Python One Line Read File</h2> <h2>Python One Line Return If</h2> <h2>Python One Line Regex Match</h2> <h2>Python One Line Recursion</h2> <h2>Python One Line Regex</h2> <h2>Python One Line Read File to List</h2> <h2>Python One Line Read Stdin</h2> <h2>Python One Line Replace</h2> <h2>Python One Line Ternary</h2> <figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"> <div class="wp-block-embed__wrapper"> <div class="ast-oembed-container"><iframe title="The Python Ternary Operator -- And a Surprising One-Liner Hack" width="1400" height="788" src="https://www.youtube.com/embed/9XXcUHXrqZ4?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </div> </figure> <p><strong>Ternary</strong> (from Latin <em>ternarius</em>) is an adjective meaning <em>“composed of three items”</em>. (<a href="https://en.wikipedia.org/wiki/Ternary" target="_blank" rel="noreferrer noopener" title="https://en.wikipedia.org/wiki/Ternary">source</a>) So, literally, the <a href="https://blog.finxter.com/python-one-line-ternary/" target="_blank" rel="noreferrer noopener" title="Python One Line Ternary">ternary operator in Python</a> is composed of three operands.</p> <p><strong>Syntax</strong>: The three operands are written in an intuitive combination <code>... if ... else ...</code>.</p> <pre class="wp-block-preformatted"><On True> if <Condition> else <On False></pre> <figure class="wp-block-table is-style-stripes"> <table> <thead> <tr> <th>Operand</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><On True></td> <td>The return expression of the operator in case the condition evaluates to <code>True</code></td> </tr> <tr> <td><Condition></td> <td>The condition that determines whether to return the <On True> or the <On False> branch.</td> </tr> <tr> <td><On False></td> <td>The return expression of the operator in case the condition evaluates to <code>False</code></td> </tr> </tbody> </table><figcaption><em>Operands of the Ternary Operator</em></figcaption></figure> <p>Let’s have a look at a minimum example in our interactive code shell:</p> <p> <iframe src="https://trinket.io/embed/python/42f3df6ddd" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p> <p><em><strong>Exercise</strong>: Run the code and input your age. What’s the output? Run the code again and try to change the output!</em></p> <h2>Python One Line Two For Loops</h2> <h2>Python One Line True False</h2> <h2>Python One Line Too Long</h2> <h2>Python One Line Two Commands</h2> <h2>Python One Line To Multiple Line</h2> <h2>Python One Line URL Decode</h2> <h2>Python One Line Or</h2> <h2>Python One Line Object</h2> <h2>Python One Line Open File</h2> <h2>Python One Line Print</h2> <h2>Python One Line Print For Loop</h2> <h2>Python One Line Print If</h2> <h2>Python One Line Print List</h2> <h2>Python One Line Parse JSON</h2> <h2>Python One Line Pretty Print JSON</h2> <h2>Python One Line Array Filter</h2> <h2>Python One Line Append</h2> <h2>Python One Line And Or</h2> <h2>Python One Line Conditional Assignment</h2> <h2>Python One Swap</h2> <h2>Python One Line Sum</h2> <h2>Python One Line Sort</h2> <h2>Python One Line Semicolon</h2> <h2>Python One Line Dictionary</h2> <h2>Python One Line Function Definition</h2> <h2>Python One Line Def</h2> <h2>Python One Line Docstring</h2> <h2>Python One Line Dict Comprehension</h2> <h2>Python One Line Double For Loop</h2> <h2>Python One Line Download File</h2> <h2>Python One Line For Loop Append</h2> <h2>Python One Line Generator</h2> <h2>Python One Line FizzBuzz</h2> <h2>Python One Line HTTP Get</h2> <h2>Python Global in One Line</h2> <h2>Python One Line Hello World</h2> <h2>Python One Line Comment</h2> <h2>Python One Line Class</h2> <h2>Python Define Two Variables in One Line</h2> <h2>Python Define Multiple Variables in One Line</h2> <h2>Python One Line If (Not) None</h2> <h2>Python One Line Map</h2></p> </div> https://www.sickgaming.net/blog/2020/07/09/python-one-line-x/ |