Amit Pandya
Amit Pandya

Reputation: 371

How to loop to generate string in sequence?

I am trying to create a loop where I can generate string using loop. What I am trying to achieve is that I want to create a small collection of strings starting from 1 character to up to 5 characters.

So, starting from sting 1, I want to go to 55555 but this is number so it seems easy if I just add them, but when it comes to alpha numeric, it gets tricky.

Here is explanation,

I have collection of alpha-numeric chars as string s = "123ABC" and what I want to do is that I want to create all possible 1 character string out of it, so I will have 1,2,3,A,B,C and after that I want to add one more digit in length of string so I can get 11, 12, 13 and so on until I get all possible combination out of it up to CA, CB, CC and I want to get it up to CCCCCC. I am confused in loop because I can get it to generate a temp sting but looping inside to rotate characters is tricky,

this is what I have done so far,

i = 0

strr = "123ABC"

while i < len(strr):
    t = strr[0] * (i+1)
    for q in range(0, len(t)):
        # Here I need help to rotate more
        pass
    i += 1

Can anyone explain me or point me to resource where I can find solution for it?

Upvotes: 2

Views: 2457

Answers (2)

Tom&#225;š Linhart
Tom&#225;š Linhart

Reputation: 10210

You may want to use itertools.permutations function:

import itertools

chars = '123ABC'
for i in xrange(1, len(chars)+1):
    print list(itertools.permutations(chars, i))

EDIT: To get a list of strings, try this:

import itertools

chars = '123ABC'
strings = []
for i in xrange(1, len(chars)+1):
    strings.extend(''.join(x) for x in itertools.permutations(chars, i))

Upvotes: 2

VPfB
VPfB

Reputation: 17247

This is a nested loop. Different depths of recursion produce all possible combinations.

strr = "123ABC"

def prod(items, level):
    if level == 0:
        yield []
    else:
        for first in items:
            for rest in prod(items, level-1):
                yield [first] + rest

for ln in range(1, len(strr)+1):
    print("length:", ln) 
    for s in prod(strr, ln):
        print(''.join(s))

It is also called cartesian product and there is a corresponding function in itertools.

Upvotes: 1

Related Questions