我必须编写一个python代码,它应该采用两个序列(s1,s2)为python中给定数量的试验生成序列2(s2)的随机字符串,并返回每个字符串(s1固定,s2更改)审判。例如:
input seq: [aabcc,aabcc]
Output seq for 4 trials:
Trial1:[aabcc, aabcc]
Trial2:[aabcc, aaabc]
Trial3:[aabcc, aaaaa]
Trial4:[aabcc, ccaab]
就像从给定输入序列中为给定数量的试验生成随机序列。有人可以帮我使用python中的基本for和while循环来编码吗? (即没有内置功能)。
答案 0 :(得分:1)
import random
# if you can't use random.choice, this is a one-for-one substitute
def random_choice(seq):
"""
Return a random element from a non-empty sequence
"""
return seq[int(random.random() * len(seq))]
def random_string_from_sample(s, length=None):
"""
Return a random string based on the letter-distribution in s
"""
if length is None:
length = len(s)
return ''.join(random_choice(s) for _ in range(length))
def main():
s0, s1 = "aabcc", "aabcc"
trials = 4
for i in range(1, trials+1):
print("Trial{}:[{}, {}]".format(i, s0, random_string_from_sample(s1)))
if __name__=="__main__":
main()
产生
Trial1:[aabcc, bbaca]
Trial2:[aabcc, cbaac]
Trial3:[aabcc, cacac]
Trial4:[aabcc, caacc]
答案 1 :(得分:0)
此解决方案提取唯一字符,因此结果不会针对输入中频率较高的字符进行加权。如果您不想要这种行为,只需删除要设置的转换。
from random import randint
s = "aabbcc"
chars = list(set(s))
nchars = len(chars)
trials = 4
for i in range(trials):
rng_sample = ''.join([chars[randint(0,nchars-1)] for _ in range(len(s))])
print rng_sample
答案 2 :(得分:0)
S1显然很容易返回。 s2可以变成一个列表并随机播放:
s2 ="aabbcc"
import random
h = list(s2)
random.shuffle(h)
newString = ''.join(h)
print (newString)