获取长度为 K 的 N 个随机非重叠子串 [英] Get N random non-overlapping substrings of length K

查看:34
本文介绍了获取长度为 K 的 N 个随机非重叠子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个长度为 20000(或其他任意长度)的字符串 R.我想从字符串 R 中获取 8 个长度为 k 的随机非重叠子字符串.

Let's say we have a string R of length 20000 (or another arbitrary length). I want to get 8 random non-overlapping sub strings of length k from string R.

我尝试将字符串 R 分成 8 个等长的分区并获取每个分区的 [:k] 但这不够随机,无法在我的应用程序中使用,并且该方法的工作条件不容易满足.

I tried to partition string R into 8 equal length partitions and get the [:k] of each partition but that's not random enough to be used in my application, and the condition of the method to work can not easily be met.

我想知道是否可以使用内置的随机包来完成这项工作,但我想不出办法,我该怎么办?

I wonder if I could use the built-in random package to accomplish the job, but I can't think of a way to do it, how can I do it?

推荐答案

您可以使用 while 循环来强制唯一性:

You can use a while loop to enforce uniqueness:

import random
result, n, k = set(), 20000, 10
for _ in range(8):
  a = random.randint(0, n-k) 
  while any(a >= i and a <= i+k for i in result):
     a = random.randint(0, n-k) 
  result.add(a)

final_result = [(i, i+k) for i in result]

输出:

[(13216, 13226), (10400, 10410), (4290, 4300), (14499, 14509), (7985, 7995), (9363, 9373), (1181, 1191), (14526, 14536)]

这篇关于获取长度为 K 的 N 个随机非重叠子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆