Created
October 24, 2019 19:30
-
-
Save JacobCallahan/dc84ccd5ec319c42f6b3291a1e628886 to your computer and use it in GitHub Desktop.
Generators and Iterators
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# generators and iterators | |
import random | |
def my_gen(in_str="This is a sentence."): | |
"""A generator that returns on character in a string per iteration""" | |
for char in in_str: | |
yield char # return one character and wait | |
def big_list(): | |
"""Create a list of number from 0 to 100 million""" | |
return list(range(100000000)) | |
def list_gen(): | |
"""A generator that gives you the same as above, but one at a time""" | |
for i in range(100000000): | |
yield i | |
# classic list comprehension | |
l_comp = [x for x in range(10)] | |
# generator comprehension. returns a generator | |
g_comp = (x for x in range(10)) | |
class AlphaIter: | |
"""This class defines a new iterator which loops over the alphabet""" | |
def __init__(self, count=10): | |
self._max = count # controls when the iterator runs out | |
self._count = 0 # keep track of current iteration nunber | |
self._pos = -1 # keep track of current alphabet position | |
self._alpha = "abcdefghijklmnopqrstuvwxyz" | |
def __iter__(self): | |
"""When something is trying to use this class as an iterator, | |
return an instance of the class | |
""" | |
return self | |
def __next__(self): | |
"""This is what runs in every iteration. Controls what is returned""" | |
if self._count >= self._max: | |
raise StopIteration # Stop iterating when we reach the max | |
if self._pos >= 25: | |
self._pos = -1 # Move back to "a" | |
self._pos += 1 # increment our counters | |
self._count += 1 | |
return self._alpha[self._pos] | |
class RandomChar(AlphaIter): | |
"""Similar to the class above, but returns a random letter""" | |
def __init__(self, count=10): | |
super().__init__(count=count) | |
def __next__(self): | |
if self._count >= self._max: | |
raise StopIteration | |
self._count += 1 | |
return random.choice(self._alpha) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment