Pulling all n-sized combinations from a list
jess.austin at gmail.com
jess.austin at gmail.com
Thu Feb 16 20:34:18 EST 2006
hi,
I'm not sure why this hasn't come up yet, but this seems to beg for
list comprehensions, if not generator expressions. All of the
following run in under 2 seconds on my old laptop:
>>> alph = 'abcdefghijklmnopqrstuvwxyz'
>>> len([''.join((a,b,c,d)) for a in alph for b in alph for c in alph for d in alph])
456976
>>> len([''.join((a,b,c,d)) for a in alph for b in alph for c in alph for d in alph
... if (a>=b and b>=c and c>=d)])
23751
>>> len([''.join((a,b,c,d)) for a in alph for b in alph for c in alph for d in alph
... if (a!=b and b!=c and c!=d and d!=a and b!=d and a!=c)])
358800
>>> len([''.join((a,b,c,d)) for a in alph for b in alph for c in alph for d in alph
... if (a>b and b>c and c>d)])
14950
cheers,
Jess
More information about the Python-list
mailing list