Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Generator Exercises

  1. The Sieve of Eratosthones (Again). Look at Sieve of Eratosthenes and Sieve of Eratosthenes. We created a list or a set of candidate prime numbers. This exercise has three parts: initialization, generating the list (or set) or prime numbers, then reporting. In the list version, we had to filter the sequence of boolean values to determine the primes. In the set version, the set contained the primes.

    Within the Generate step, there is a point where we know that the value of p is prime. At this point, we can yield p. If yield each value as we discover it, we eliminate the entire "report" step from the function.

  2. The Generator Version of rangeThe range function creates a sequence. For very large sequences, this consumes a lot of memory. You can write a version of range which does not create the entire sequence, but instead yields the individual values. Using a generator will have the same effect as iterating through a sequence, but won't consume as much memory.

    Define a generator, genrange, which generates the same sequence of values as range, without creating a list object.

    Check the documentation for the built-in function xrange.

  3. Prime Factors. There are two kinds of positive numbers: prime numbers and composite numbers. A composite number is the product of a sequence of prime numbers. You can write a simple function to factor numbers and yield each prime factor of the number.

    Your factor function can accept a number, n, for factoring. The function will test values, f, between 2 and the square root of n to see if the expression n % f == 0 is true. If this is true. then the factor, f, divides n with no remainder; f is a factor.

    Don't use a simple-looking for -loop; the prime factor of 128 is 2, repeated 7 times.


 
 
  Published under the terms of the Open Publication License Design by Interspire