processing limitation in Python

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Feb 15 07:06:42 EST 2006


On Wed, 15 Feb 2006 10:16:07 +0000, Dennis Lee Bieber wrote:

> 	Why bother collecting the "factors" into a list only to print them
> at the bottom of the procedure -- you aren't returning a value from
> factor(), so I'd suggest dropping the 
> 	factors = []
> and
> 	print factors
> 
> replace
> 	factors.append(d)
> with
> 	print d	#optional , if you want as many on a line as possible

This is generally bad practice. You now have a function which can't
easily feed its output into any other function (without pipes, file
redirection and other tricks). The function is now locked down into one
rather limited use: printing the factors.

If you need the factors one at a time, the right way is to use a
generator, and yield them as they are found. Otherwise, the correct way to
solve this problem is to accumulate all the factors in a list and return
the list.


> 	Among other things, besides not needing memory to store the entire
> list, you also get to see it working as each one is found and printed.

The amount of memory needed to store the entire list is trivial for all
but the hugest numbers. A number with 1,000 factors would be enormous,
and yet the memory needed for a list of 1,000 ints could be as small as
8K -- trivial on modern computers.


-- 
Steven.




More information about the Python-list mailing list