Reputation: 1022
I am trying to generate a pattern whose vocabulary can consist of only 'A', 'B', 'C', 'D' or '*'
, characters can repeat any number of times but the catch is that resulting the pattern must have at least one letter.
I tried with random module and this is the closest I came to what I want:
random.sample(set(vocabulary), 5)
Out[30]: ['A', 'D', '*', 'B', 'C']
Ideally I would like to see output like:
A***
ABAB
ABC*
and so on
how can I go about this?
Upvotes: 1
Views: 77
Reputation: 647
chars=['A', 'B', 'C', 'D', '*']
s=""
L = len(chars)
for i in range(0,5):
s += chars[random.randrange(0,L)]
# now ensure that a character is present by setting a random character
s[random.randrange(0,5)] = chars[random.randrange(0,L-1)]
Upvotes: 0
Reputation: 107347
Actually you want the product of your list element, you can use itertools.product
:
>>> from itertools import product
>>> voc=['A', 'B', 'C', 'D', '*']
>>> for pro in product(voc,repeat=5):
... print ''.join(pro)
*AAAA
*AAAB
*AAAC
*AAAD
*AAA*
*AABA
*AABB
*AABC
.
.
And if you just want to get ride of equal subsets you can use the following list comprehension, for example:
>>> voc=['C', 'D', '*']
>>> list(product(voc,repeat=3))
[('C', 'C', 'C'), ('C', 'C', 'D'), ('C', 'C', '*'), ('C', 'D', 'C'), ('C', 'D', 'D'), ('C', 'D', '*'), ('C', '*', 'C'), ('C', '*', 'D'), ('C', '*', '*'), ('D', 'C', 'C'), ('D', 'C', 'D'), ('D', 'C', '*'), ('D', 'D', 'C'), ('D', 'D', 'D'), ('D', 'D', '*'), ('D', '*', 'C'), ('D', '*', 'D'), ('D', '*', '*'), ('*', 'C', 'C'), ('*', 'C', 'D'), ('*', 'C', '*'), ('*', 'D', 'C'), ('*', 'D', 'D'), ('*', 'D', '*'), ('*', '*', 'C'), ('*', '*', 'D'), ('*', '*', '*')]
>>> list(i for i in product(voc,repeat=3)if len(set(i))>1)
[('C', 'C', 'D'), ('C', 'C', '*'), ('C', 'D', 'C'), ('C', 'D', 'D'), ('C', 'D', '*'), ('C', '*', 'C'), ('C', '*', 'D'), ('C', '*', '*'), ('D', 'C', 'C'), ('D', 'C', 'D'), ('D', 'C', '*'), ('D', 'D', 'C'), ('D', 'D', '*'), ('D', '*', 'C'), ('D', '*', 'D'), ('D', '*', '*'), ('*', 'C', 'C'), ('*', 'C', 'D'), ('*', 'C', '*'), ('*', 'D', 'C'), ('*', 'D', 'D'), ('*', 'D', '*'), ('*', '*', 'C'), ('*', '*', 'D')]
Upvotes: 2