0

I’ve been looking for an efficient Python code to generate 10 character alphanumeric strings. The string should start from “AA0AA0000A” and should increase the sequence from right to left

The code I've tried:

import string
from itertools import permutations as p

alpha = string.ascii_uppercase
num = string.digits

for a, b in p(alpha, 2):
    for c in p(num, 1):
        for d, e in p(alpha, 2):
            for f, g, h, i in p(num, 4):
                for j in p(alpha, 1):
                    print(a, b, c, d, e, f, g, h, i, j)

and the output sample I got:

A B ('0',) A B 0 1 2 3 ('A',)
A B ('0',) A B 0 1 2 3 ('B',)
A B ('0',) A B 0 1 2 3 ('C',)

But the output I expect is like

A A 0 A A 0 0 0 0 A
A A 0 A A 0 0 0 0 B
A A 0 A A 0 0 0 0 C

Is there a better or efficient way to generate the sequence of strings?

1
  • Is the question about why some of the elements are printed out in a tuple format and you wanted them to be strings or is the question about efficiency? If the former, then it is because permutations method returns a tuple docs.python.org/2/library/itertools.html#itertools.permutations. If latter, then you need to define efficiency - are you after faster execution, big-O, etc. Commented Mar 27, 2020 at 16:03

1 Answer 1

3

You probably want itertools.product:

from itertools import product

# ...
for p in product(alpha, alpha, num, alpha, alpha, num, num, num, num, alpha):
    print(*p)

Note, however, that this loop will never end (or after 1188137600000 iterations if you have the time) =) So you might want to go for a generator function to make handling easier:

def gen():
    for p in product(alpha, alpha, num, alpha, alpha, num, num, num, num, alpha):
        yield ''.join(p)

>>> g = gen()
>>> next(g)
'AA0AA0000A'
>>> next(g)
'AA0AA0000B'
>>> next(g)
'AA0AA0000C'
Sign up to request clarification or add additional context in comments.

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.