2

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?

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

3 Comments

It kinda works, but not the way I expected. For example, for 3 character string, I can have 122 or AAA but this is not giving that as a string or for six character string not CCCCCC.
try combinations_with_replacement() instead permutations. docs
It kinda solved my problem but I found one more thing, for 2 character string, i get 11, 12, 13, and than 22, 23 and than 33. not 21, not 31, 32.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.