Thursday, January 5, 2012

Python 3 examples and Explanations: Generator Function


 Generator pattern are incredibly important and useful pattern  in python. It actually creates an iterator.

 Reference code is:

#this is a general function
def isprime(n);
            if n == 1:
                        return False
            for x in range(2,n):
                        if n % x == 0;
                                    return False
            else:
                        return True

# this is a generator function
def primes(n = 1):
            while(True):
                        if isprime(n): yield n
                        n += 1


#for loop
for n in primes():
            if n > 100: break
            print(n)

Explanations:

Generator Function looks like normal function at first glance. In fact, it is a general function except that it has a ‘yield’ statement. ‘yield’ is like ‘return’ in function. In normal function here, ‘return’ returns a Boolean (True or False), and in generator function, ‘yield’ returns a value (an integer value n). And next time the function is called, it continues execution after the ‘yield’.

 In this case, we have a while loop and it checks whether a number is prime or not. If the number is not prime, it increments the number and checks the next one. And if the number is prime, then it yields, and that will return a value. The next time the function is called, it just increments the number (i.e executes after the yield).

Because of the use of ‘yield’ , it returns an iterator object that is suitable to use in for loop. The for loop calls the generator function, i.e primes. For each iteration, it puts the value in n, and checks if the value exceeds 100. Hence, the for loop uses the generator function as an iterator and generates a list of prime numbers.

If you encounter any problem, then feel free to ask the question via the comment box.

No comments: