0

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).

8
  • 1
    generate random strings for sequence 2. Can you please explain how? Commented Feb 9, 2014 at 15:31
  • Hi, for eg: abcde, then aabcd,abcee,adbce,aaacd and so on.... for given number of trials....
    – Shraddha
    Commented Feb 9, 2014 at 15:34
  • 1
    I am sorry. I am still failing to see a pattern here. Are you sure it should be randomly generated? Commented Feb 9, 2014 at 15:36
  • 1
    Not using any build in functions don't seem feasible. You'd at least have to use some kind of random number generator.
    – M4rtini
    Commented Feb 9, 2014 at 15:36
  • yes, it should be random but should contain only alphabets from the input sequence.
    – Shraddha
    Commented Feb 9, 2014 at 15:37

3 Answers 3

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()

produces:

Trial1:[aabcc, bbaca]
Trial2:[aabcc, cbaac]
Trial3:[aabcc, cacac]
Trial4:[aabcc, caacc]
0

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
0

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)
1
  • Thank you.. Can this be implemented without using .append, .shuffle an d .join??
    – Shraddha
    Commented Feb 9, 2014 at 19:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.