all possible combinations
John Machin
sjmachin at lexicon.net
Thu Jul 14 17:52:22 EDT 2005
rbt wrote:
> Thanks to all who were helpful... some of you guys are too harsh and
> cynical.
Reality check: wander down to your nearest military establishment, ask a
drill sergeant to demonstrate "harsh and cynical".
> Here's what I came up with. I believe it's a proper
> combination, but I'm sure someone will point out that I'm wrong ;)
>
> groups = [list('abc'),list('abc'),list('abc'),list('abc')]
>
> already = []
In general, a set would be better than a list (1) conceptually (2) when
the number of elements is large.
>
> while 1:
>
> LIST = []
Read the style guide -- http://www.python.org/peps/pep-0008.html
>
> for g in groups:
> sample = random.sample(g, 1)
> LIST.append(sample[0])
>
> STRING = ''.join(LIST)
> if STRING not in already:
> print STRING
> already.append(STRING)
> if len(already) == 81:
> break
>
You don't need to use random sampling. Paul Rubin has shown how it can
be done deterministically. The following is a generalisation of his
code; it generates all possible assemblies of size n from a list of
parts. Is this helpful?
def all_size_n_knickers(rqd_size, pieces):
npieces = len(pieces)
knicker_count = npieces ** rqd_size
austen = [npieces ** (rqd_size-k-1) for k in xrange(rqd_size)]
for i in xrange(knicker_count):
knicker = [pieces[j] for j in [(i // d) % npieces for d in austen]]
yield knicker
for alist in all_size_n_knickers(4, 'abc'):
print ''.join(alist)
print
print list(all_size_n_knickers(2, [1, 42, 666]))
More information about the Python-list
mailing list