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
while word[letter] == i[letter]: IndexError: string index out of range
In input :
same('hello',['hi,'hell','helo'])
Output:
'hell'
Thanks
Advertisement
Answer
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