Skip to content

Instantly share code, notes, and snippets.

@adriaanbd
Last active August 12, 2019 04:28
Show Gist options
  • Save adriaanbd/f111cd79a38d109b8132e659616cba31 to your computer and use it in GitHub Desktop.
Save adriaanbd/f111cd79a38d109b8132e659616cba31 to your computer and use it in GitHub Desktop.
generators created by adriaanbd - https://repl.it/@adriaanbd/generators
name = "john joe doe dole"
names = name.split()
my_list = names
for item in names:
print(item)
# Generators are iterators but you can only iterate over them once, because they do not store all values in memory and generate the values on the fly
my_generator = (x*x for x in range(3))
for item in my_generator:
print(item)
# yield is a keyword used like return, except the function will return a generator
def create_generator():
my_list = range(3)
for item in my_list:
# you can insert a condition here
yield item*item
my_generator = create_generator()
print(my_generator)
for item in my_generator:
print(item)
# An example. Look at how it only goes through the iterable once (DOESN'T WORK, FIGURE OUT WHY):
class Bank():
crisis = False
def create_atm(self):
while not self.crisis:
yield "$100"
hsbc = Bank()
corner_street_atm = hsbc.create_atm()
print(corner_street_atm.__next__())
print(corner_street_atm.__next__())
print([corner_street_atm.__next__() for cash in range(5)]) # if you increment the number it will keep printing the money
hsbc.crisis = True # crisis is coming, no more money!
print(corner_street_atm.__next__())
wall_street_atm = hsbc.create_atm() # it's even true for new ATMs
print(wall_street_atm.__next__())
hsbc.crisis = False # trouble is, even post-crisis the ATM remains empty
print(corner_street_atm.__next__())
brand_new_atm = hsbc.create_atm() # build a new one to get back in business
print([brand_new_atm.__next__() for cash in range(5)])
['$100', '$100', '$100', '$100', '$100']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment