Generate permutations

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Generate permutations

Snuffy Dog
I am wanting to generate data for all permutations of n variables each of which can have any value from 1 through j inclusive. For example, for n=8 variables and j=7 values (that is, 1,2,3,4,5,6,7) the number of permutations with replacement will equal 7 to the 8th power, or 7*7*7*7*7*7*7*7 = 5,764,801 permutations. Note that I'm after permutations and not combinations. Ideally I'm wanting a macro where n and j can take on any value but I would settle for a macro where n = 10 and j = 7. 
 
Any help would be greatly appreciated.
 
Jonathon
 
 
Reply | Threaded
Open this post in threaded view
|

Re: Generate permutations

Albert-Jan Roskam
Hello!

The following will only work with Python 2.6 or higher. Is this what you are looking for?

import csv, itertools
def makePerms(csvFileName, values, n_vars, verbose = False):
    with open(csvFileName, "wb") as f:
        csv_writer = csv.writer(f, delimiter = "\t")
        for cnt, element in enumerate(itertools.product(values, repeat = n_vars)):
            csv_writer.writerow(element)
            if verbose and cnt % 10**5 == 0:
                print "... Writing record %s" % cnt
        print "Done: %s records written" % cnt
makePerms("d:/temp/perms.csv", range(7), 8, True)

There's also an itertools.permutations function, but I think you need the above.

Cheers!!
Albert-Jan

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--- On Sat, 7/31/10, Snuffy Dog <[hidden email]> wrote:

From: Snuffy Dog <[hidden email]>
Subject: [SPSSX-L] Generate permutations
To: [hidden email]
Date: Saturday, July 31, 2010, 12:38 AM

I am wanting to generate data for all permutations of n variables each of which can have any value from 1 through j inclusive. For example, for n=8 variables and j=7 values (that is, 1,2,3,4,5,6,7) the number of permutations with replacement will equal 7 to the 8th power, or 7*7*7*7*7*7*7*7 = 5,764,801 permutations. Note that I'm after permutations and not combinations. Ideally I'm wanting a macro where n and j can take on any value but I would settle for a macro where n = 10 and j = 7. 
 
Any help would be greatly appreciated.
 
Jonathon