The code below takes dna_string2 and matches it within dna_string1. It then outputs the index location of the match or matches and then increments then return value by 1 to simulate "counting itself". The problem I am facing is that I need the output values of 2, 4, and 10 to be assigned to their own variables. I cannot figure out how to separate the output so that I can assign to individual variables. I have tried using split(). I have tried writing to a file first. I feel like I have tried just about everything to get the output separated. Any expert help would be greatly appreciated.
defined function
def get_most_likely_ancestor(dna_string1, dna_string2):
i = 0
g = len(dna_string2)
for i in range (len(dna_string1)):
i = 1
g = 1
if (dna_string1[i:g]) == (dna_string2):
locations = dna_string1.index(dna_string2, i)
locations = 1
return locations
Function input
dna_string1 = "GATATATGCATATACTT"
dna_string2 = "ATAT"
function output (exactly as shown)
2
4
10
CodePudding user response:
The function needs to be more flexible to allow for any number of matches.
The function should not be responsible for presentation of the result.
Therefore, let's just return a list and handle the presentation in the caller. For example:-
def get_most_likely_ancestor(s1, s2):
offset = 0
olist = []
while (i := s1[offset:].find(s2)) >= 0:
olist.append(offset := offset i 1)
return olist
for pos in get_most_likely_ancestor('GATATATGCATATACTT', 'ATAT'):
print(pos)
Output:
2
4
10
CodePudding user response:
If you know how many values the function returns, you can assign each to a separate variable.
first, second, third = get_most_likely_ancestor(dna_string1, dna_string2)
The right-hand side of the assignment needs to be a sequence which can be unpacked into exactly the number of expressions on the left-hand side.
If you can't predict how many values the function will return, it's one of nature's many ways to tell you this is a bad idea anyway. You are in fact much better off with all the values in a single variable which is a list (or, depending on your use case, perhaps a dictionary, or a more complex data structure, probably encapsulated in a class).
CodePudding user response:
I guess this could help you with your project:
def get_most_likely_ancestor(dna_string1, dna_string2):
i = 0
g = len(dna_string2)
global list_plain
list_plain = []
for i in range (len(dna_string1)):
i = 1
g = 1
if (dna_string1[i:g]) == (dna_string2):
locations = dna_string1.index(dna_string2, i)
locations = 1
list_plain.append(locations)
dna_string1 = "GATATATGCATATACTT"
dna_string2 = "ATAT"
get_most_likely_ancestor(dna_string1,dna_string2)
print(list_plain)
I agree with @tripleee. Encapsulating them in a class is a better idea for larger or unknown data.