0

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!!!

2
  • homework? There is a homework tag, FYI. Commented Sep 21, 2010 at 4:38
  • I have added "homework" tag. If it is not, please remove it. Commented Sep 21, 2010 at 4:45

4 Answers 4

1

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]
Sign up to request clarification or add additional context in comments.

3 Comments

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]
Annyway this is i think a better solution than mine :)
@armonge: yours is very good too, I like both :) thanks guys a lot
0

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

2 Comments

It should be noted that the find method is deprecated in 3.0.
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.
0

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.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.