Hi all,
given a sequence of n elements i need to generate all possible permutations of length k <= n.

I found an elegant way to do this recursively:

def comb(items, n):
    if n==0: yield []
    else:
        for i in xrange(len(items)):
            for cc in comb(items[i+1:],n-1):
                yield [items[i]]+cc

However, this is way too slow for my needs. I try to use this to generate all possible 5 card poker hands, but this takes around 17 seconds on an Athlon 2200. That's a 2 orders of magnitude too slow for my needs.

I am familiar with writing Python extensions in C++, but I will not do this until I am confident that it is the only way to get the speed I need.

Any of you excellent sirs have any suggestions on how I can speed this up?

Please find attached an example script that executes and times the poker hand generation.


--
Frode, SIM

"Any fool can write code that a computer can understand.
 Good programmers write code that humans can understand"
import sys
from timeit import Timer

def comb(items, n):
    if n==0: yield []
    else:
        for i in xrange(len(items)):
            for cc in comb(items[i+1:],n-1):
                yield [items[i]]+cc


def test():
    cards = range(52)
    for hand in comb(cards, 5):
        "do something with the hand"        

def main(argv):
    t = Timer("test()", "from __main__ import test")
    print t.timeit(1)


if __name__=="__main__":
    sys.exit(main(sys.argv[1:]))
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to