views:

67

answers:

4

I have an assignment said that to create a findString function that accept 2 string which are 'target' and 'query', and that returns 
a 
list
 of 
all 
indices 
in 
target
 where 
query 
appears. 
If 
target 
does 
not 
contain 
query,
return 
an 
empty
 list.


For example: findString(‘attaggtttattgg’,’gg’)

return:

[4,12]

I dont know how to start off with this function writing at all. Please help me everyone. Thank you so much!!!

A: 

def find_string(search, needle): start = -1 results = []

while start + 1< len(search):
    start = search.find(needle, start +1)

    if start == -1:
        break

    results.append(start )

return results
armonge
It should be noted that the find method is deprecated in 3.0.
Dominic Bou-Samra
thank you very much but as we input search and needle into that (), does it mean to make this function to accept 2 arguments right? Sorry for asking this but I am totally a newbie to python and programming. Thank you very much.
pmt0512
A: 

Here are a couple of hints to get you started.

  1. target.find(query) will return the index of query in target. If query is not found, it will return -1.

  2. A string can be sliced. target[pos:] will give you a substring of target starting from pos.

Manoj Govindan
A: 

This may require some error handling:

def find_allPatterns(strVal, strSub):
    listPos = []
    strTemp = strVal

    while True:
        try:
            posInStr = strTemp.index(strSub)
        except ValueError:
            posInStr = None
        if posInStr:
            listPos.append(posInStr)
            subpos = posInStr + len(strSub)
            strTemp = strTemp[subpos:]
        else:
            break

    return listPos

print find_allPatterns('attaggtttattgg', 'gg')

Output:

[4, 6]
pyfunc
+1  A: 

since an answer has already been given:

def find_matches(strng, substrng):
    substrg_len = len(substr)
    return [i for i in range(len(strg) + 1 - substrg_len) 
            if strg[i:i+substrg_len] == substrg]
aaronasterling
wow, this is very nice and simple. Thank you very much
pmt0512
def find_matches(strg, substr): substrg_len = len(substr) return [i for i in range(len(strg)+1 - substrg_len) if strg[i:i+substrg_len] == substr]
armonge
Annyway this is i think a better solution than mine :)
armonge
@armonge. good looking out.
aaronasterling
@armonge: yours is very good too, I like both :) thanks guys a lot
pmt0512