Create an account


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

#1
Python One Line Generator

<div><p><strong><em>A generator function is a Pythonic way to create an iterable without explicitly storing it in memory.</em></strong> This reduces memory usage of your code without incurring any additional costs.</p>
<p>The following code shows a function <code>get_numbers(n)</code> that returns a <a href="https://blog.finxter.com/python-lists/" target="_blank" rel="noreferrer noopener" title="The Ultimate Guide to Python Lists">list </a>of <code>n</code> <a href="https://blog.finxter.com/python-random-module/" target="_blank" rel="noreferrer noopener" title="Python’s Random Module – Everything You Need to Know to Get Started">random </a>numbers. </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 random # NOT A GENERATOR!
# Create and return a list of numbers
def get_numbers(n): numbers = [] for i in range(n): numbers.append(random.random()) # List of n elements exists in memory return numbers # Sum up 1000 random numbers
s = 0
for x in get_numbers(1000): s += x
print(s)</pre>
<p>However, this is not very efficient code because you create a list in advance without need. What if you had 1,000,000,000 numbers? Your memory would quickly fill up! </p>
<p>A better way is to use a generator function with the <code>yield</code> keyword that creates the random numbers dynamically as they are iterated over:</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 random # GENERATOR
# Generate numbers one by one
def generate_numbers(n): for i in range(n): yield random.random() # Sum up 1000 random numbers
s = 0
for x in generate_numbers(1000): s += x
print(s)</pre>
<p>There are two big advantages to using a generator: </p>
<ul>
<li>(1) You don’t have to create a huge list first and store it in memory but generate the next element as you iterate over it. </li>
<li>(2) It’s shorter and more concise. </li>
</ul>
<p>However, it may not be concise enough for you! <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;" /> So, here’s the problem addressed in this article:</p>
<hr class="wp-block-separator"/>
<p><strong>Problem</strong>: Can we write a one-line generator?</p>
<p>Let’s dive into different methods to accomplish this!</p>
<h2>Method 1: One-Liner Generator Function</h2>
<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(sum(random.random() for i in range(1000)))</pre>
<p>The code consists of the following parts:</p>
<ul>
<li>The <code><a href="https://blog.finxter.com/the-separator-and-end-arguments-of-the-python-print-function/" title="Python Print Function [And Its SECRET Separator &amp; End Arguments]" target="_blank" rel="noreferrer noopener">print()</a></code> function prints the result of the expression to the shell. </li>
<li>The <code><a href="https://blog.finxter.com/python-one-line-sum-list/" title="Python One Line Sum List" target="_blank" rel="noreferrer noopener">sum()</a></code> function sums over all values in the following iterable.</li>
<li>The generator expression <code>random.random() for i in range(1000)</code> generates 1000 random numbers and feeds them into the outer sum() function without creating all of them at once.</li>
</ul>
<p>This way, we still don’t store the whole list of 1000 numbers in memory but create them dynamically. </p>
<h2>Method 2: exec()</h2>
<p>The following method is not pretty—but it solves the problem to create a generator in a single line of 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="">exec('def g(n):\n for i in range(n):\n yield random.random()')
</pre>
<p>The <code><a href="https://blog.finxter.com/how-to-execute-multiple-lines-in-a-single-line-python-from-command-line/" title="How to Execute Multiple Lines in a Single Line Python From Command-Line?" target="_blank" rel="noreferrer noopener">exec()</a></code> function can be used to one-linerize every Python code snippet under the sun. Just pass the code you want to run as a string and replace all newlines with the newline character <code>'\n'</code>. This way, you can create a generator function <code>g(n)</code> that dynamically creates <code>n</code> random numbers. You can now iterate them using the standard code snippet:</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="">s = 0
for x in g(1000): s += x
print(s)
# 488.318368852096</pre>
<p>Because the numbers are random, the output will be different for you. You can try it yourself in our interactive shell:</p>
<p> <iframe height="600px" width="100%" src="https://repl.it/@finxter/CriticalPinkBracket?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<p><em><strong>Exercise</strong>: What’s the output for you? Why is it different than ours?</em></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 loading="lazy" 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/...generator/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016