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

Count number of letters until one letters has changed

I want to count number of same letter at beginning between two words (letter by letter) until there’s one different and return who has the most same letter.

This is my code :

def same(word, liste):
    letter = 0
    dico = dict()
    for i in liste:
        while word[letter] == i[letter]:
            letter += 1;
        dico[i] = letter;
        letter = 0;
    
    same = max(dico, key=dico.get)
    return same

But i get always this error of string index out of range, I’ve tried with much way but nothing

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

    while word[letter] == i[letter]:

IndexError: string index out of range

In input :

same('hello',['hi,'hell','helo'])

Output:

'hell'

Thanks

>Solution :

you can’t go out of range in your while
verify the length of your word before word[letter] == i[letter]
while letter < len(word) and letter < len(i) and word[letter] == i[letter]:

gives you :

def same(word, liste):
    letter = 0
    dico = dict()
    for i in liste:
        while letter < len(word) and letter < len(i) and  word[letter] == i[letter]:
            letter += 1;
        dico[i] = letter;
        letter = 0;
    
    same = max(dico, key=dico.get)
    return same

print(same('blablabla',['blaze','bli']))

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