Search code examples
pythoncombinationspython-itertools

How can i start itertools combinations from specific letter/digit?


I have a code like this:

start = 1
end = 2
for length in range(start, end+1):
    for c in itertools.combinations_with_replacement(string.ascii_letters + string.digits, length):

this will print every uppercase/lowercase letter from A to Z and after all letters are finished, It will start printing all digits from 0 to 9. so it looks like this: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789

After first cycle is done, it goes on second one and does the same thing. like this:

First cycle starting: a

Second cycle starting: aa

and etc.

what i want it to do:

I want to start combinations from specific letter or digit.

Like this:

Combination 1:

First cycle starting: b

Second cycle starting: ba

If it is not possible, then like this:

Combination 2:

First cycle starting: b

Second cycle starting: bb


Solution

  • I think you're asking for all possible permuations after a certain index in which case you can do:

    import string
    import itertools
    
    chars = string.ascii_letters + string.digits
    
    def alpha_perms(index):
    
        return list(itertools.permutations(chars[index:]))
    
    print(alpha_perms(0)) #0th index to go along with the below statement
    

    Although... this will most likely (absolutely) freeze your machine. There are 62 characters in chars thats 62! (62 factorial) which is approximately equal to 3.1469973e+85 or ~π*10^85th power possible combinations assuming you passed in the 0th index. Even a reasonable index is going to take a long time.

    Alternatively, since using return list(...) will cause problems for high combination possibilities. You could yield the value

    import string
    import itertools
    
    chars = string.ascii_letters + string.digits
    
    def alpha_perms(index):
    
        for perm in itertools.permutations(chars[index:]):
             yield perm