I' ve got problem like this one for example i have list which I' m generating and number of possible duplicates m :
n = 4 # num of random elements in list (which are letters)
m = 2 # num of possible duplicates of letter if that's more than m the
given letter need to be swapped for another one which doesn't disrupts logic
['A', 'A', 'B', 'B'] # and now "B" is generated so this need be automatically swapped
I have to generate another letter which is not for example "A" because than len of A will be == 3
example output:
['A', 'A', 'B', 'B', 'C']
That the way I tryed to solve it
# n is number of elements,
# m is number of possible duplicates
# both are generated before
import string
import random
from collections import Counter
@classmethod
def generate_string(cls, n, m):
return [random.choice(string.ascii_uppercase) if j > m else i for i, j in
Counter([random.choice(string.ascii_uppercase) for _ in range(0, n)]).items()]
CodePudding user response:
So it sounds like you want a randomly generated list of length n
consisting of of letters where no letter is repeated more than m
times. If so, you can duplicate your list of letters m
times so that there is exactly m
copies of each letter, and then take a random sample of size n
from that population:
from string import ascii_uppercase as alpha
import random
def generate_letters(n, m):
return random.sample(alpha * m, n)
Demos:
In [4]: generate_letters(10, 2)
Out[4]: ['O', 'I', 'C', 'R', 'V', 'Z', 'P', 'F', 'D', 'L']
In [5]: generate_letters(5, 3)
Out[5]: ['B', 'S', 'J', 'B', 'O']
In [6]: generate_letters(9, 5)
Out[6]: ['S', 'V', 'D', 'O', 'K', 'U', 'W', 'Z', 'C']
CodePudding user response:
import random
import string
n = #
m = #
rand_list = []
for _ in range(n):
rand_char = (random.choice(string.ascii_uppercase))
while rand_list.count(rand_char) >= m:
rand_char = (random.choice(string.ascii_uppercase))
rand_list.append(rand_char)
print(rand_list)