在26个英文字母和空格中随机抽取,看多久可以写出目标字符串
import xzc_tools.tools
import string
import random
# 随机字符池
char_list = list(string.ascii_letters)
char_list.append(' ')
# 随机字符串
random_str = []
# 目标字符串
goal_str = 'methinks it is a weasel'
def get_random_str(str_length, old_random_str):
try:
global random_str
if len(old_random_str) != str_length:
random_str = random.sample(char_list, str_length)
else:
for j in range(str_length):
if list(goal_str)[j] != old_random_str[j]:
old_random_str[j] = ''.join(random.sample(char_list, 1))
random_str = old_random_str
return random_str
except Exception as msg:
xzc_tools.tools.printInfo(2, msg)
return ''
def compare_str(str_1, str_2):
try:
if str_1 == ''.join(str_2):
return 1
else:
return 0
except Exception as msg:
xzc_tools.tools.printInfo(2, msg)
return -1
if __name__ == '__main__':
flag = 0
num = 0
while flag == 0:
num = num + 1
new_random_str = get_random_str(23, random_str)
if new_random_str != '':
flag = compare_str(goal_str, new_random_str)
print(num, random_str)