Reputation: 183
I have to write a python code which should take two sequences (s1,s2) generate random strings for sequence 2 (s2) for a given number of trials in python and return both strings (s1 fixed, s2 changed) for each trial. For ex:
input seq: [aabcc,aabcc]
Output seq for 4 trials:
Trial1:[aabcc, aabcc]
Trial2:[aabcc, aaabc]
Trial3:[aabcc, aaaaa]
Trial4:[aabcc, ccaab]
It is like generating random sequence from the given input sequence for the given number of trials. Can someone help me code this using basic for and while loops in python? (i.e no built in functions).
Upvotes: 0
Views: 215
Reputation: 11
S1 is obviously easy to return. s2 can be turned into a list and shuffled:
s2 ="aabbcc"
import random
h = list(s2)
random.shuffle(h)
newString = ''.join(h)
print (newString)
Upvotes: 0
Reputation: 56624
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()
produces:
Trial1:[aabcc, bbaca]
Trial2:[aabcc, cbaac]
Trial3:[aabcc, cacac]
Trial4:[aabcc, caacc]
Upvotes: 1
Reputation: 13539
This solution extracts the unique characters, so the result won't be weighted against the characters with higher frequency in the input. If you don't want that behavior, just remove the conversion to set.
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
Upvotes: 0