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

If the character is in the string, return the sum of the indices that the character occurs

I am new to python and taking an intro class, one of my homework asks to write a function that takes, as arguments, a string and a character. If the character is in the string, return the sum of the indices that the character occurs. Otherwise, return False. We can not use the find() or index() built-in functions.

This is my code so far

def addIndices(myString, myChar):
    summy= 0
    for i in myChar:
        if i not in myString:
            return False 
    else:
        for i in myString:
            if i in myString:
                summy += 1
    return summy

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

>Solution :

Here is an example code. Note you said to return the sum of indices, so you need to add the index (starting at 0) of each matching character, not just to add 1 for each matching character.

#!/usr/bin/env python

def addIndices(myString, myChar):
    summy = 0
    if not myChar in myString:
         return False
    else:
        i = 0
        for ch in myString:
            if myChar == ch:
                summy += i
            i += 1
    return summy

sum = addIndices('it is a test', 'i')

print(sum)
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