tags:

views:

76

answers:

4

I have the following code:

import string
import random

d =[random.choice(string.uppercase) for x in xrange(3355)]
s = "".join(d)

print s

At the moment it prints out a random sequence of letters from the alphabet. But, i need it to print out a sequence of letters containing only four letters for example 'A', 'C', 'U', 'G'. How would this be accomplished?

Thanks

Quinn

+1  A: 

just replace string.uppercase with the sequence (list or string, for example) containing your choices.

SilentGhost
+1  A: 

Change the set you are asking random.choice to pick from:

import string
import random

d =[random.choice('ACUG') for x in xrange(3355)]
s = "".join(d)

print s
Jon-Eric
you don't need a list comprehension there
SilentGhost
A: 

Your question is not clear. Do you mean that you want to choose a string only 4 in length? If so then do:

d =[random.choice(string.uppercase) for x in xrange(4)]

Or if you want to choose from a list of only four choices, then do:

d =[random.choice("ACUG") for x in xrange(3355)]
Aaron
A: 

I think the OP is wanting to pre-select a 4-character sample from string.uppercase, then create a 3355 item string based on that:

import string
import random

num_samples = 4
char_sample = random.sample(string.uppercase, num_samples)
d =[random.choice(char_sample) for x in xrange(3355)]
s = "".join(d)

print s
print char_sample

In this case, random.sample(population, sample_count) will take care of that first requirement quite nicely.

However, I agree with the other answers/comments that this question is a bit vague.

vizionary