1

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
  • Are you making random RNA sequences? Commented Mar 6, 2010 at 21:36

4 Answers 4

2

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

import random

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

print s

Edit: As SilentGhost points out, if your ultimate goal is only to make a string, skipping the intermediate list is more memory-efficient:

s = "".join(random.choice('ACUG') for x in xrange(3355))
Sign up to request clarification or add additional context in comments.

1 Comment

you don't need a list comprehension there
1

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

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.