Problem with algorithm

Paul Rubin http
Fri Apr 13 01:58:50 EDT 2007


Charles Sanders <C.delete_this.Sanders at BoM.GOv.AU> writes:
> Forgive any silly mistakes I have made (I've been teaching
> myself python for about 1 week) but there is a moderately
> well known algorithm for this that extends to arbitrary
> lengths of both the list of alternatives and the length
> of the required output, and avoids deeply nested loops.

    s = "abcd"

    def a(n):
        if n==0:
            yield ''
            return
        for c in s:
            for r in a(n-1):
                yield c+r

    print list(a(3))



More information about the Python-list mailing list