Count number of letters until one letters has changed

Question:

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

Asked By: Kev74

||

Answers:

I would just use a list comprehension along with basic substring logic:

def same(word, liste):
    return max([x for x in liste if x in word], key=len)

print(same('hello',['hi','hell','helo']))  # hell
Answered By: Tim Biegeleisen

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
Answered By: Lola Eracléas

A combination of zip, sum and max should give you the result –

def same(word, liste):
  pairs = [zip(word, x) for x in liste]
  match_len = [sum([x == y for x, y in pair]) for pair in pairs]
  return lst[match_len.index(max(match_len))]
Answered By: Mortz

Yet an other solution:

def same(word, liste):

def get_score(word, other):
    for i, (l1, l2) in enumerate(zip(word, other)):
        if l1 != l2:
            break
    return i

scores = {other:get_score(word, other) for other in liste}
return max(scores, key=scores.get)

In this case, I define the function get_score to count the number of common letters in a pair of words. I am sure to not run in IndexError because of the zip that makes an iterator over the 2 words.
Then I just did the same as you to get the word associated with the greatest score.

Answered By: Fab-B
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.