all possible combinations

George Sakkis gsakkis at rutgers.edu
Thu Jul 14 17:48:34 EDT 2005


"rbt" <rbt at athop1.ath.vt.edu> wrote:

> Thanks to all who were helpful... some of you guys are too 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 = []
>
> while 1:
>
>     LIST = []
>
>     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

UGH! I guess you're right, it's theoretically correct in the limit;
however IIRC, in your original post you were asking about the most
efficient way, not the least efficient, most obscure and inextensible
solution one could come up with. You're hoping to generate all
combinations AT RANDOM and you're wondering why some of us come out
"too harsh and cynical" ?! Try this with all letters instead of 'abc'
and when it ends get back to us, or rather our grand-grandchildren. In
the meantime, learn about recursion, generators and accumulating loops
and try to understand the right, efficient solutions already posted.

Cynically yrs,

George

PS: Btw, using ALL_CAPITALS (at least for local variables) is BAD
STYLE; the same holds for variables named 'list' and 'string',
independent of case.




More information about the Python-list mailing list