all possible combinations

George Sakkis gsakkis at rutgers.edu
Wed Jul 13 14:05:35 EDT 2005


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

> Say I have a list that has 3 letters in it:
>
> ['a', 'b', 'c']
>
> I want to print all the possible 4 digit combinations of those 3
> letters:
>
> 4^3 = 64


It's actually 3^4 = 81 (3 candidates/choice ** 4 choices)

> aaaa
> abaa
> aaba
> aaab
> acaa
> aaca
> aaac
> ...
>
> What is the most efficient way to do this?


I don't know if it's *the most* efficient -- and I don't think it really matters -- but it's fast,
short and sweet:

def iterPermutations(num, seq):
    if num:
        for rest in iterPermutations(num-1, seq):
            for item in seq:
                yield rest + [item]
    else:
        yield []


for comb in iterPermutations(4, list("abc")):
    print ''.join(comb)


George






More information about the Python-list mailing list