Generating 'random' string from a different string in python? -
i'm trying generate random string using elements of different string, same length.
ex) string: agaacgc
i want random string using elements string above
right have:
import random seq = 'agaacgc' length = len(seq) blah in range(len(seq)): #apologies lame variable names x = random.randint(0,length - 1) print seq[x] and of course give me like:
a
a
g
a
c
a
a
how alter program prints out random string on 1 line?
i'm hoping relatively simple answer, i'm still beginner in python, don't want fancy. @ appreciated.
and there way repeat randomization 'n' number of times?
say instead of 1 random string, wanted 4 random strings on different lines. there easy way doing this? (my newbish mind telling me repeat loop 'n' times...but needs changeable number of randomized strings)
sorry asking. i'd appreciate help. i'm stuck on bigger problem because don't know how these steps.
in python 3, there simple way print character without newline, in python 2, there isn't.* so, simplest way build string, print @ end:
result = '' blah in range(len(seq)): #apologies lame variable names x = random.randint(0,length - 1) result += seq[x] print result * there 2 less simple ways: can use from __future__ import print_function , use python 3 print syntax instead of python 2, or can use sys.stdout.write(seq[x]) each character , sys.stdout.write('\n') , sys.stdout.flush() @ end. don't think want either of those.
however, there number of ways improve this:
- use
randrange(length)instead ofrandint(0, length - 1). - use
random.choice(seq)instead of usingrandrangeorrandintin first place. - use
_instead ofblah"don't care" variables.* - if don't care you're iterating over, you're iterating once each character,
for _ in seq:, notfor _ in range(len(seq)):. - build list of letters, call
''.join()@ end, instead of building string. - use comprehension instead of explicit loop.
putting together:
print ''.join(random.choice(seq) _ in seq) * unless you're using gettext i18n, or else gives _ special meaning. projects come own convention "don't care" names—maybe __, or dummy. , of course blah fine such project, long used consistently.
as repeating it, newbish mind right; use loop. example (taking second version, it'll work first):
n = 4 _ in range(n): print ''.join(random.choice(seq) _ in range(len(seq))) that'll print out 4 different random strings. , if set n 100, it'll print 100 different random strings.
you may want write in function:
def print_random_strings(seq, n): _ in range(n): print ''.join(random.choice(seq) _ in range(len(seq))) and can call like:
print_random_strings(seq, 4) but either way, basic intuition right on track.
Comments
Post a Comment