Reputation: 3851
I want to generate all the random strings having length varying from 1 till max_length. Is is there an in-built function in python that would do that? If not, please tell me how to do this or direct me to posts which covers this type of problem. Thanks in advance.
Upvotes: 2
Views: 912
Reputation: 250921
you can use random.sample()
:
In [28]: from string import ascii_lowercase as asl
In [29]: import random
In [30]: max_length=10
In [31]: for x in xrange(1,max_length+1):
....: ''.join(random.sample(asl,x))
....:
....:
Out[31]: 'k'
Out[31]: 'jy'
Out[31]: 'ldo'
Out[31]: 'ivlr'
Out[31]: 'gqelt'
Out[31]: 'gbvnqw'
Out[31]: 'baestog'
Out[31]: 'kyijhmvn'
Out[31]: 'toshxklwb'
Out[31]: 'wihtmouexg'
Upvotes: 2
Reputation: 179392
Random strings:
import random
def get_random_string(alphabet, slen):
return ''.join(random.choice(alphabet) for _ in xrange(slen))
print get_random_string('0123456789', 5) # prints e.g. 62247
All strings in lexicographical order (thanks @DSM for reminding me about itertools
):
import itertools
def gen_all_strings(alphabet, slen):
it = itertools.product(alphabet, repeat=slen)
return (''.join(s) for s in it)
print list(gen_all_strings('abc', 2)) # prints ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
Upvotes: 3