简体   繁体   English

生成只有两个特定字符的随机字符串

[英]Generating a Random String with only two specific characters

I need to generate a fixed-length string with only 'y' and 'n' in a random order, and the number of 'n' in the string is determined by the variable Njk.我需要生成一个只有'y'和'n'的随机顺序的定长字符串,字符串中'n'的个数由变量Njk决定。 The strings must be like 'yyyyynynynyyyyyy' or 'yynyyyynyyynyyyy', and I'll generate a huge amount of strings.字符串必须类似于“yyyyynynynyyyyyy”或“yynyyyynyyynyyyy”,我将生成大量字符串。 Currently I'm doing like the code below.目前我正在做下面的代码。 The problem is, to generate 200 strings of length 16, it works fine, but when I try to generate 200 strings of length 33, it takes so much time to execute that is making my work unviable.问题是,要生成 200 个长度为 16 的字符串,它工作正常,但是当我尝试生成 200 个长度为 33 的字符串时,执行需要花费太多时间,这让我的工作变得不可行。 How can I do it in a optimal/efficient way?我怎样才能以最佳/有效的方式做到这一点?

Best regards!最好的祝福!

# #
 chaves = 16 Njk = 3 #Generating a random key state def rand_estado(): aux2 = randint(0,1) if aux2 == 0: estado = 'n' if aux2 == 1: estado = 'y' return estado #Generating a random combination of key states with fixed number of 'y' and 'n' def rand_estado_chaves(): radialidade = 0 #The condition that must be satisfied while (radialidade:= chaves - Njk): estado_chaves = "" #For each key for i in range(chaves). estado_chaves += rand_estado() radialidade = estado_chaves.count('y') return estado_chaves

If you know the size of the final string and the number of N, you can create a list that starts with Njk N and length - Njk Y. Then, shuffle the list and join it.如果你知道最终字符串的大小和 N 的数量,你可以创建一个以Njk N 和length - Njk Y 开头的列表。然后,打乱列表并加入它。

from random import shuffle

final_size = 16
number_of_n = 3

# ['n', 'n', 'n', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y', 'y']
result = list('n' * number_of_n + 'y' * (final_size - number_of_n))
shuffle(result)
result = ''.join(result)
print(result)

This can output strings like this:这可以像这样的 output 字符串:

nyyyyyyyynyynyyy nyyyyyyyynyynyyy

nyyyyyyynyyyynyy nyyyyyyynyyyynyy

ynyynynyyyyyyyyy yyyyyyyyyyyyy

You can generate random strings with only 2 characters using random.choices by setting the weights.您可以通过设置权重使用random.choices生成仅包含 2 个字符的随机字符串。 If you get more or fewer n s than you need, discard and get a new one.如果你得到的n比你需要的多或少,丢弃并得到一个新的。 Below I did that with a recursive function.下面我用递归 function 做了这个。

import random

def yn_gen(num_n=5, size=30):
    candidate = random.choices('yn', 
        weights=((size-num_n)/size, num_n/size), 
        k=size)
    if candidate.count('n')==num_n:
        return ''.join(candidate)
    else:
        return yn_gen(num_n, size)

yn_gen()
# returns:
'yynnnnyyyyyyyyyyyyyyyyyyyynyyy'

yn_gen(10, 50)
# returns:
'yynynynnyyyyynyyyyyyynyynnyyyyyyyyyynyynyyyyyyyyyy'

Essentially, you need to choose the pre-defined number of positions where n s should be placed, and set everything else to y :本质上,您需要选择应放置n的预定义位置数,并将其他所有内容设置为y

def generate(length, ns):
    result = ['y'] * length
    for i in random.sample(range(length), ns):
        result[i] = 'n'
    return ''.join(result)

The random module provides a function called sample that can be used to produce the random patterns very efficiently random 模块提供了一个名为 function 的sample ,可用于非常有效地产生随机模式

from random import sample

size    = 33
count   = 200
NjK     = 7

yn      = ["n"]*NjK + ["y"]*(size-NjK)
results = [ "".join(sample(yn,size)) for _ in range(count) ]

print(results[:3],"...",results[-3:])

this will allow you to generate thousands of long patterns very fast.这将使您能够非常快速地生成数千个长模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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