Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find index positions of a substring using Python

Very new to Python here, and struggling. Any help is appreciated! Confession: this is obviously a request for help with homework, but my course ends tomorrow and the instructor takes too long to return a message, so I’m afraid if I wait I won’t get this finished in time.

I’m using a learning module from Cornell University called introcs. It’s documented here: http://cs1110.cs.cornell.edu/docs/index.html

I am trying to write a function that returns a tuple of all indexes of a substring within a string. I feel like I’m pretty close, but just not quite getting it. Here’s my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


import introcs 

def findall(text,sub):
    result = ()
    x = 0
    pos = introcs.find_str(text,sub,x)

    for i in range(len(text)):
        if introcs.find_str(text,sub,x) != -1:
            result = result + (introcs.find_str(text,sub,x), )
            x = x + 1 + introcs.find_str(text,sub,x)

    return result

On the call findall(‘how now brown cow’, ‘ow’) I want it to return (1, 5, 10, 15) but instead it lops off the last result and returns (1, 5, 10) instead.

Any pointers would be really appreciated!

>Solution :

You don’t need to loop over all the characters in text. Just keep calling introcs.find_str() until it can’t find the substring and returns -1.

Your calculation of the new value of x is wrong. It should just be 1 more than the index of the previous match.

Make result a list rather than a tuple so you can use append() to add to it. If you really need to return a tuple you can use return tuple(result) at the end to convert it.

def findall(text,sub):
    result = []
    x = 0
    while True:
        pos = introcs.find_str(text,sub,x)
        if pos == -1:
            break
        result.append(pos)
        x = pos + 1

    return result
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading