I am new to python and trying to write a python function that generates random n-mers (each character can be one of (ACGT) in the end. But the while loop seems to go on forever. Any suggestions? Here is my code:
def add_base(x):
random_seqs = []
for char in "ACGT":
y = x char
random_seqs.append(y)
return random_seqs
def random_n_mer(n):
print("Random " str(n) " mers")
i = 1
random_mers_next = []
random_mers = add_base("")
while i < n:
for base in random_mers:
print(base)
random_mers_next.extend(add_base(base))
print(random_mers)
print(random_mers_next)
random_mers = random_mers_next
i = i 1
random_n_mer(3)
CodePudding user response:
The reason why your while loop goes on forever is that you set your random_mers
variable to random_mers_next
. Inside your for loop for the random_n_mer(n)
function, you extend random_mers_next
making the list longer. After, you say that random_mers
is equal to that list. Since the for loop is iterating through each value in the random_mers
list, and you keep adding to that list, it will never end.
CodePudding user response:
I will go on a limb here and guess:
you're missing
random_mers_next = []
So try this:
while i < n:
for base in random_mers:
print(base)
random_mers_next.extend(add_base(base))
print(random_mers)
print(random_mers_next)
random_mers = random_mers_next
random_mers_next = []
i = i 1
Without it you're rapidly extending random_mers - on every i
iteration you process previously produced elements twice, which adds exponential growth on top of 4 times growth by the algorithm itself.