I have been successful in generating random strings, but I am now looking to make sure there are a couple of repeating strings and a couple of blank strings. My current code looks like
import random
import string
import numpy as np
def randomGenerator(length):
# for i in range(0,16):
randomString = ''.join(random.choice(string.ascii_uppercase string.digits) for i in range(length))
return randomString
for i in range(0,16):
listOne = [randomGenerator(8)]
mat = np.array([listOne])
print(mat)
The output I get:
[['3DYKRYHV']]
[['D78NVRZ1']]
[['4BLPD8IB']]
[['D94C73DQ']]
[['1ZDIC5AJ']]
[['XEEEV4JP']]
[['PM9WQ0WM']]
[['4CK2O7F5']]
[['D4GEPXI8']]
[['MVWNOMY5']]
[['TOSS2USW']]
[['1DCQ5JV0']]
[['UR8UUPL7']]
[['17Y7ZIWF']]
[['EABGQ1X3']]
[['KZVBAZRM']]
The output I am looking For:
[['3DYKRYHV']]
[['D94C73DQ']]
[[' ']]
[['D94C73DQ']]
[['1ZDIC5AJ']]
[[' ']]
[['PM9WQ0WM']]
[['3DYKRYHV']]
[['D4GEPXI8']]
[['3DYKRYHV']]
[['UR8UUPL7']]
[['1DCQ5JV0']]
[['UR8UUPL7']]
[[' ']]
[['EABGQ1X3']]
[['KZVBAZRM']]
Or something close to that. I am need the some strings to repeat and some empty slots.
CodePudding user response:
Just use the same logic:
import random
import string
import numpy as np
def randomGenerator(length):
# for i in range(0,16):
randomString = ''.join(random.choice(string.ascii_uppercase string.digits) for i in range(length))
return randomString
last_generated = None
for i in range(0,16):
random_one = randomGenerator(8)
listOne = random.choice([[random_one],[' '*8],[last_generated]])
last_generated = random_one
mat = np.array([listOne])
print(mat)
output:
[['1X1HB4G9']]
[[' ']]
[['Z5NLBY94']]
[['0QDD90L9']]
[['T0LHDTHF']]
[['T0LHDTHF']]
[['DCG1P5K5']]
[['UDH8IJJF']]
[['UDH8IJJF']]
[['LLHVVL5J']]
[['NWWG7DHC']]
[['NWWG7DHC']]
[[' ']]
[['QQ96U7UR']]
[['WE71CM5X']]
[['OA46GGMN']]
CodePudding user response:
#Note: random.choices()
has a parameter k
to indicate how many items to pick. It is "with replacement" which means an item can be picked again. So you don't need to use random.choice()
in a loop.
#Use if-elif-else
block to choose whether to add a random string, a blank string, or a duplicate string according to specified percentages.
import random
import string
import numpy as np
LIST_LENGTH = 16
STR_LENGTH = 8
PERCENT_RANDOM = 70
PERCENT_BLANK = 18
def random_string_generator(length):
randomString = ''.join(random.choices(string.ascii_uppercase string.digits, k=length))
return randomString
list_one = [[random_string_generator(STR_LENGTH)]]
while len(list_one) < LIST_LENGTH:
chance = random.randrange(100)
if chance < PERCENT_RANDOM:
list_one.append([random_string_generator(STR_LENGTH)])
elif chance < PERCENT_RANDOM PERCENT_BLANK:
list_one.append([' '*STR_LENGTH])
else:
list_one.append(random.choice(list_one))
mat = np.array(list_one)
print(mat)