generating canonical list of tuples?

Joshua Muskovitz joshm at taconic.net
Thu Jan 3 16:28:05 EST 2002


Here's what I'm trying to do...

create "magicFunction(limit, dimension)" to return a list of tuples.  Each
tuple contains exactly "dimension" elements, all positive integers.  The sum
of these elements must be less than or equal to "limit".

for example, magicFunction(5,3) should return:
[ (1,1,1), (1,1,2), (1,1,3), (1,2,1), (1,2,2), (1,3,1), (2,1,1), (2,1,2),
(2,2,1), (3,1,1) ]

The order of the resulting tuples is unimportant.

If "dimension" is a fixed number, this is easy.  In the case where dimension
is 3, this can be written as:

[ (a,b,c) for a in range(1,4) for b in range (1,5-a) for c in
range(1,6-a-b) ]

But (and here is the REAL question)...  how does one do this when dimension
is a variable?

Option 1:  Recursion.  Recursion will cause a memory explosion when the
limit and dimension begin to grow, and so this isn't a good solution.
Option 2:  Exec.  Construct a line of python code dynamically based on the
above example, and exec it.  Would this be considered a good solution?
Option 3:  ???

Is there a pythonic way of doing this?

-- josh




-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----==  Over 80,000 Newsgroups - 16 Different Servers! =-----



More information about the Python-list mailing list