简体   繁体   中英

Generate random element from list with no more than one repetition of one element

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?

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')]
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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM