Iterations, that is, repeating things many times, Python allows you to iterate over sequences, dictionaries, and other objects with a for loop. When other objects are iterated, you need to implement the __iter__ method in other objects.
The __iter__ method returns an iterator, which is the object with the next method. When the next method is called, the iterator returns its next value. If the next method is invoked, but the iterator has no value to return, a Stopiteration exception is thrown.
Implementing a Fibonacci sequence with an iterator
Class Fab (object):
def __init__ (Self,max):
Self.max = Max
SELF.N, self.a, self.b = 0, 0, 1
def __iter__ (s ELF): Return
self
def next (self):
if SELF.N < self.max:
r = self.b
self.a, self.b = self.b, SELF.A + self.b
SELF.N + + + 1 return
R
raise stopiteration
print ' iterator output: ' For
I in Fab (5):
Print I
Output results:
In addition to being able to iterate over iterators and iterated objects (which is often done), they can also be converted to sequences. In most cases where a sequence can be used, an iterator can be used to replace it.
A generator, an iterator defined by a common function syntax, is a function that contains a yield statement. In addition to the name difference, its behavior and ordinary functions are also very different. This is because it does not produce the return value as returns, but rather produces multiple values at a time. Each time a value is generated (using the yield statement), the function opportunity is frozen: the function stops at that point waiting to be activated. When the function is activated, it starts at the point where it stopped. The local variable for the function is the same as the state of the last run.
Implement the Fibonacci sequence with the generator.
Def FAB (max):
N, a, b = 0, 0, 1 while
n < max:
yield b
A, B = B, a + b
n = n + 1
print ' generator generated knot Fruit: ' For
I in Fab (5):
Print I
Use the generator to solve the N queen problem.
def config (state, nextx):
nexty = Len (state) to
I in range (nexty):
if ABS (Nextx-state[i]) in (0,nexty-i): return
True
/False
def nqueens (num = 8, state = ()):
If Len (state) = = Num-1: For
POS in range (num):
if not config (state, POS):
yield (POS)
else:
to POS in range (num):
if not config (state, POS):
for result in Nqueens (num, state + (pos.)):
yield (POS,) + result
def prettyprint (solution):
def line (pos, lenth = Len (solution)): "Return
". ' * (POS) + ' X ' + '. ' * (lenth-pos-1) for
pos in solution:
Print Line (pos)
i = 1 for
solution in Nqueens ():
print ' first %d placement '% (i)
prettyprint (solution)
i + + 1