Skip to content
Advertisement

Outputting on multiple lines and I need each line to be assigned to its own variable

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement