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

A generator function is a Pythonic way to create an iterable without explicitly storing it in memory. This reduces memory usage of your code without incurring any additional costs.

The following code shows a function get_numbers(n) that returns a list of n random numbers.

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)

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!

A better way is to use a generator function with the yield keyword that creates the random numbers dynamically as they are iterated over:

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)

There are two big advantages to using a generator:

  • (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.
  • (2) It’s shorter and more concise.

However, it may not be concise enough for you! ? So, here’s the problem addressed in this article:


Problem: Can we write a one-line generator?

Let’s dive into different methods to accomplish this!

Method 1: One-Liner Generator Function


print(sum(random.random() for i in range(1000)))

The code consists of the following parts:

  • The print() function prints the result of the expression to the shell.
  • The sum() function sums over all values in the following iterable.
  • The generator expression random.random() for i in range(1000) generates 1000 random numbers and feeds them into the outer sum() function without creating all of them at once.

This way, we still don’t store the whole list of 1000 numbers in memory but create them dynamically.

Method 2: exec()


The following method is not pretty—but it solves the problem to create a generator in a single line of code.

exec('def g(n):\n for i in range(n):\n yield random.random()')

The exec() 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 '\n'. This way, you can create a generator function g(n) that dynamically creates n random numbers. You can now iterate them using the standard code snippet:

s = 0
for x in g(1000): s += x
print(s)
# 488.318368852096

Because the numbers are random, the output will be different for you. You can try it yourself in our interactive shell:

Exercise: What’s the output for you? Why is it different than ours?

Python One-Liners Book


Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners 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.

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:

  Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  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
  Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

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.

Get your Python One-Liners Now!!



https://www.sickgaming.net/blog/2020/09/...generator/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? xSicKxBot 0 8 10-16-2020, 10:30 PM
Last Post: xSicKxBot
  [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 18 10-10-2020, 08:24 PM
Last Post: xSicKxBot
  [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 18 10-09-2020, 06:13 PM
Last Post: xSicKxBot
  [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 29 10-02-2020, 04:24 AM
Last Post: xSicKxBot
  [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 31 10-01-2020, 02:21 AM
Last Post: xSicKxBot
  [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? xSicKxBot 0 32 09-29-2020, 09:02 PM
Last Post: xSicKxBot
  [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 34 09-28-2020, 02:36 AM
Last Post: xSicKxBot
  [Tut] How To Format A String That Contains Curly Braces In Python? xSicKxBot 0 31 09-25-2020, 07:51 PM
Last Post: xSicKxBot
  [Tut] Python One Line Dictionary xSicKxBot 0 38 09-21-2020, 05:58 PM
Last Post: xSicKxBot
  [Tut] Python Import Error (ModuleNotFoundError) xSicKxBot 0 33 09-20-2020, 04:15 PM
Last Post: xSicKxBot

Forum Jump:

Become a Patron!
[-]
Upcoming Events

[-]
Latest Threads
News - Destiny 2 Hotfix 2.9.2.2
Last Post: xSicKxBot
Today 01:53 PM
» Replies: 0
» Views: 1
News - The Video Game History Foundation...
Last Post: xSicKxBot
Today 01:52 PM
» Replies: 0
» Views: 2
News - French charity steam Z Event rais...
Last Post: xSicKxBot
Today 01:52 PM
» Replies: 0
» Views: 2
News - Borat 2 Review Roundup: Very Nice...
Last Post: xSicKxBot
Today 11:18 AM
» Replies: 0
» Views: 3
Mobile - Win yourself a free copy of sha...
Last Post: xSicKxBot
Today 09:07 AM
» Replies: 0
» Views: 3
[Tut] Top 3 Freelance Developer Contract...
Last Post: xSicKxBot
Today 04:49 AM
» Replies: 0
» Views: 3
(Indie Deal) Alien Cat Bundle, RIDE 4 re...
Last Post: xSicKxBot
Today 04:48 AM
» Replies: 0
» Views: 5
News - Super Smash Bros. Ultimate 9.0.1...
Last Post: xSicKxBot
Today 04:48 AM
» Replies: 0
» Views: 4
Unity Mega Bundle X 10th Anniversary Sal...
Last Post: xSicKxBot
Today 01:02 AM
» Replies: 0
» Views: 4
Microsoft - Fundraising and Engagement f...
Last Post: xSicKxBot
Today 01:02 AM
» Replies: 0
» Views: 3

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020