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
CodePudding user response:
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
CodePudding user response:
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
CodePudding user response:
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))]
CodePudding user response:
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.
CodePudding user response:
Maybe try this:
def same(word):
lst = word.split("")
letter = sorted(lst, key=lambda x: lst.count(x), reverse=True)[0]
return lst.count(letter[0])