|
| 1 | +#! /usr/bin/python |
| 2 | + |
| 3 | +# e-satis @ stackoverflow: http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained |
| 4 | + |
| 5 | +# Iteration : Going over items in a list, one-by-one |
| 6 | + |
| 7 | +myList=[1,2,3] |
| 8 | +for i in myList: # "for X in Y" is an iteration pattern |
| 9 | + print i, |
| 10 | +print |
| 11 | + |
| 12 | +# The retrieval of the next item using the iterator is done by calling its next() method. |
| 13 | + |
| 14 | +#========== |
| 15 | +print |
| 16 | + |
| 17 | +# Iterables |
| 18 | +# In the example above, 'myList' is an iterable object, because it comprises items which can be iterated over. |
| 19 | + |
| 20 | +myList2= [ x*x for x in range(3)] # creating a list using list comprehension |
| 21 | +for i in myList2: # every Y you can use "for X in Y" on is an iterable: Arrays (lists/tuples/dictionaries/strings), files, ... (this independence of variable type is called duck typing: "If it walks like a duck...") |
| 22 | + print i, |
| 23 | +print |
| 24 | + |
| 25 | +# Iterating over an iterable is repeatable and non-destructive of the iterable. |
| 26 | +# The iterable objects become very large if all possible values need to be stored in memory in advance. |
| 27 | + |
| 28 | +#===================================================================== |
| 29 | +print |
| 30 | + |
| 31 | +# Generators: Iterators which generate the iteration values on-the-fly |
| 32 | +# i.e. the values are not all stored in memory in advance, |
| 33 | +# but can only be iterated over once. |
| 34 | + |
| 35 | +myGenerator=(x*x for x in range(3)) |
| 36 | +print myGenerator # 'myGenerator' is an initerable 'generator object' |
| 37 | +for i in myGenerator: |
| 38 | + print i, |
| 39 | +print |
| 40 | + |
| 41 | +# Once this 'for' loop reaches its end, you can't 'for i in myGenerator' again... |
| 42 | +# 'myGenerator' evaluates inside the loop, not before it (lazy evaluation) |
| 43 | +# this improves performace, especially for large lists. |
| 44 | + |
| 45 | +print "Timing. This may take a few seconds..." |
| 46 | +import timeit |
| 47 | +print timeit.timeit('sum(xrange(200))',setup='') # uses generator |
| 48 | +print timeit.timeit('sum(range(200))',setup='') # does not use generator |
| 49 | + |
| 50 | + |
| 51 | +#============================================================================= |
| 52 | +print |
| 53 | + |
| 54 | +# Yield: a keyword used like 'return', in a function which returns a generator |
| 55 | +# c.f. function returning a function object |
| 56 | + |
| 57 | +def createGenerator(): |
| 58 | + myList3=range(3) |
| 59 | + for i in myList3: |
| 60 | + yield i*i # this function returns the generator '(i*i for i in range(3))' |
| 61 | + |
| 62 | +myGenerator=createGenerator() |
| 63 | +print myGenerator # 'myGenerator' is an initerable 'generator object' |
| 64 | +for i in myGenerator: |
| 65 | + print i, |
| 66 | +print |
| 67 | + |
| 68 | + |
| 69 | +#=================================== |
| 70 | +print |
| 71 | + |
| 72 | +# Controlling a generator exhaustion |
| 73 | + |
| 74 | +#create Bank class, which can create ATMs |
| 75 | +class Bank(): |
| 76 | + crisis=False |
| 77 | + def create_atm(self): |
| 78 | + while not self.crisis: |
| 79 | + yield "$100" |
| 80 | + |
| 81 | +#when everything's OK, the ATM gives you as much money as you want (each iterative withdrawls yields $100) |
| 82 | +bank=Bank() |
| 83 | +beforeCrisisATM=bank.create_atm() |
| 84 | +print [beforeCrisisATM.next() for i in range(9)] |
| 85 | + |
| 86 | +# Create a crisis, so that new ATM's will not be able to dispense cash |
| 87 | +bank.crisis=True |
| 88 | +try: |
| 89 | + print beforeCrisisATM.next() |
| 90 | +except StopIteration: |
| 91 | + print "beforeCrisisATM threw StopIteration exception!" |
| 92 | + |
| 93 | +# Creating a new ATM won't help, because the bank is still in crisis |
| 94 | +duringCrisisATM=bank.create_atm() |
| 95 | +try: |
| 96 | + print duringCrisisATM.next() |
| 97 | +except StopIteration: |
| 98 | + print "duringCrisisATM threw StopIteration exception!" |
| 99 | + |
| 100 | +# The trouble is, even post-crisis, the ATMs remain empty, |
| 101 | +# because once the generator ran out for watever reason |
| 102 | +# (e.g. due to an if/else statement such as in the Bank() case) |
| 103 | +# there is no place for the iterator to pick up, and the generator is dead. |
| 104 | +bank.crisis=False |
| 105 | +try: |
| 106 | + print beforeCrisisATM.next() |
| 107 | +except StopIteration: |
| 108 | + print "beforeCrisisATM threw StopIteration exception!" |
| 109 | +try: |
| 110 | + print duringCrisisATM.next() |
| 111 | +except StopIteration: |
| 112 | + print "duringCrisisATM threw StopIteration exception!" |
| 113 | + |
| 114 | +# However, if we now build another ATM, this new one doesn't know about the past crisis |
| 115 | +postCrisisATM=bank.create_atm() |
| 116 | +print postCrisisATM.next() |
| 117 | +print postCrisisATM.next() |
| 118 | +print postCrisisATM.next() |
| 119 | + |
| 120 | + |
| 121 | +#===================== |
| 122 | +print |
| 123 | + |
| 124 | +# The itertools module |
| 125 | +import itertools |
| 126 | + |
| 127 | +# e.g. possible orders of arrival for a 4 horse race (i.e. all permutations of four items) |
| 128 | +horses=[1,2,3,4] |
| 129 | +races=itertools.permutations(horses) |
| 130 | +print races |
| 131 | +print list(races) |
| 132 | + |
| 133 | + |
| 134 | +#================== |
| 135 | +print |
| 136 | + |
| 137 | +# Generator Pattern |
| 138 | + |
| 139 | +class FirstN(object): |
| 140 | + def __init__(self, n): |
| 141 | + self.n=n |
| 142 | + |
| 143 | + def __iter__(self): |
| 144 | + return self |
| 145 | + |
| 146 | +#sumOfFirstN=sum(FirstN(100)) |
| 147 | + |
| 148 | +#=========== |
| 149 | +print |
| 150 | + |
| 151 | +# Example: Fibonacci sequence (http://stackoverflow.com/questions/3953749/python-fibonacci-generator) |
| 152 | + |
| 153 | +fibSeqLength = int(raw_input("Enter Fibonacci sequence length:")) |
| 154 | + |
| 155 | +# Iteration generation using the yield keyword: |
| 156 | +# This implementations do not store the entire sequence, and therefore the memory taken does not scale with 'fibSeqLength' |
| 157 | +def fibYield(): |
| 158 | + a, b = 0, 1 # base case |
| 159 | + while True: |
| 160 | + yield a # return a generator to iterate 'a' |
| 161 | + a, b = b, a + b # promote values of the next elements in the sequence |
| 162 | + |
| 163 | +a=fibYield() # 'a' is now the object returned by 'fibYield()' -- a generator |
| 164 | + |
| 165 | +for i in range(fibSeqLength): # loop for all elements in input range |
| 166 | + print a.next(), # print the value of the next iteration |
| 167 | +print |
| 168 | + |
| 169 | +# Using iteration over list data-structure |
| 170 | +# Since this implementation stores the entire sequence to a list, its memory requirement scales with 'fibSeqLength' |
| 171 | +def fibList(n): |
| 172 | + a, b = 0, 1 |
| 173 | + for i in xrange(n): |
| 174 | + yield a |
| 175 | + a, b = b, a + b |
| 176 | + |
| 177 | +print list(fibList(fibSeqLength)) |
| 178 | + |
| 179 | +# Using anaylitical golden ratio expression: |
| 180 | + |
| 181 | +sqrt5=pow(5,0.5) |
| 182 | +goldenRatio=(1 + sqrt5)/2 |
| 183 | + |
| 184 | +def fibGoldenRatio(n): |
| 185 | + return int( (pow(goldenRatio, n) - pow(1-goldenRatio, n))/sqrt5) |
| 186 | + |
| 187 | +for n in range(fibSeqLength): |
| 188 | + print fibGoldenRatio(n), |
| 189 | +print |
| 190 | + |
| 191 | +#=========================================================== |
| 192 | +print |
| 193 | + |
| 194 | +# Example: Self expanding binary tree search for node values distanced in given range from some reference object ('distance' in this respect is defined elswhere) |
| 195 | + |
| 196 | +# In the following example we will use the extend() keyword: |
| 197 | +myList4=['a','b'] |
| 198 | +myList5=['c','d'] |
| 199 | +myList4.extend(myList5) |
| 200 | +print myList4 |
| 201 | + |
| 202 | +print |
| 203 | +# Prequisites: |
| 204 | +class node(object): # 'node' object class |
| 205 | + _values, _median = 0, 0# some attributes of this node |
| 206 | + _leftchild=None # reference to left child node, if one exists |
| 207 | + _rightchild=None # reference to right child node, if one exists |
| 208 | + |
| 209 | + def _get_dist(self, obj): # somehow claculates the "distance" between the node and some reference object 'obj' |
| 210 | + pass |
| 211 | + |
| 212 | + def _get_child_candidates(self, distance, min_dist, max_dist): # 'node' object method returning generators to iterate over children, if there are any (threfore called child candidates) |
| 213 | + if self._leftchild and distance - max_dist < self._median: # if there exists a child on the node's left, and the distance to it is small enough, generate an iterator |
| 214 | + yield self._leftchild |
| 215 | + if self._rightchild and distance + max_dist >= self._median: # equivalent for child on node's right |
| 216 | + yield self._rightchild |
| 217 | + # If the function arrives here, the generator will be considered empty (there are only two children at most -- a binary tree) |
| 218 | + |
| 219 | + |
| 220 | +# Caller (from within some other function): |
| 221 | +result, candidates = list(), [self] # Create an empty list and a list with the current object reference |
| 222 | +while candidates: # Loop on children candidates (starting from the head node) |
| 223 | + node = candidates.pop() # Get the last candidate and remove it from the list |
| 224 | + distance = node._get_dist(obj) # Get the distance between the candidate node and some reference object 'obj' |
| 225 | + if distance <= max_dist and distance >= min_dist: # If the candidate node's distance from the reference object is in the range [min_dist:max_dist], add the candidate node values to the result list (uses the 'extend' keyword) |
| 226 | + result.extend(node._values) |
| 227 | + candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) # extend the list of candidates by executing the generator function above to get the child candidates of the current node. Thus, the loop will keep running until it will have looked at all the children of the children of the children, etc. of the head node |
| 228 | +#return result |
0 commit comments