How to make a function return a list of indices of the characters in the second string that appears in the first string?

后端 未结 4 1671
孤街浪徒
孤街浪徒 2021-01-25 08:54
def get_indices_from_the_second_string(string1, string2):
    \'\'\'(str, str) -> list of int
    >>> get_indices_from_the_second_string(\'AGTACACGTTAC\', \'         


        
相关标签:
4条回答
  • 2021-01-25 09:31
    def get_indices_from_the_second_string(string1, string2):
        acc = []
        s2_counter = 0
        for i, letter in enumerate(string1):
            if letter == string2[s2_counter]:
                acc.append(i)
                s2_counter += 1
                if len(acc) == len(string2):
                    break
        return acc
    
    a = get_indices_from_the_second_string('GAATTCCGTTAC', 'GAATTC')
    
    0 讨论(0)
  • 2021-01-25 09:39

    Use the built in function zip, along with another built in enumerate

    acc = []
    for i, (a, b) in enumerate(zip(string1, string2)):
        if a==b:
            acc.append(i)
    return acc
    
    0 讨论(0)
  • 2021-01-25 09:47

    Remove lines

                i += 1
                r += 1
    

    as for loops increase i and r automatically.

    And then modify your code:

    lower = 0                             # from this index will be string1 searched
    
    for i in range(0, len(string2)):
        for r in range(lower, len(string1)):
            if string1[r] == string2[i]:
                acc.append(r)
                lower = r + 1             # indexes from 0 to r are already used
                break
            elif r == len(string1) - 1:   # last index did not match
                return acc
    return acc
    
    0 讨论(0)
  • 2021-01-25 09:48

    Oh, I see what you're doing.

    def get_indices_from_the_second_string(string1, string2):
        acc = []
        string1_index = 0
        for char in string2:
            while string1[string1_index] != char:
                string1_index += 1
                if string1_index >= len(string1):
                    return acc
            acc.append(string1_index)
            string1_index += 1
            if string1_index >= len(string1):
                return acc
        return acc
    
    0 讨论(0)
提交回复
热议问题