Search code examples
pythonstringpython-itertools

Continue creating list of the possible strings in python


Possible Duplicate:
Using itertools.product and want to seed a value

I have this code, which generates a consistent list of strings.

import itertools
choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
for length in range(0,20):
    for entry in itertools.product(choices, repeat = length):
        string = ''.join(entry)
        print string

I want to be able to continue running this script from the last known string. How is this possible to do?


Solution

  • Assuming you have the variable string set as the last known string (or '' to start at beginning):

    import itertools
    choices = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
    for length in range(len(string), 20):
        itr = itertools.product(choices, repeat = length)
        if string != '' and length == len(string):
            itr = itertools.dropwhile(tuple(string).__ne__, itr)
        for entry in itr:
            string = ''.join(entry)
            print string
    

    Note that the first element this will print is the last known string. If you want to skip the last known and start by printing the next string, you could do next(itr) inside of the if statement.

    This assumes that you are trying to resume where you left off on multiple executions of a script, or other scenarios where a generator solution isn't applicable. If you can use a generator, you should.