I need to count how many excact letter in a word. E.g i need to count the letter "i" in these word. And i need to find which word has the most "i" letter in it.
list = ['box', 'computer', 'sheep', 'family', 'illegal', 'bubble', 'lamp', 'circuit', 'building', 'plant', 'these', 'cup']
def fgv(list):
counter= 0
maximal = 0
word= "x"
for e in list:
counter = 0
if e.__contains__("i"):
for i in range (len(e)):
if e[i] == "i":
couner += 1
if counter < maximal:
maximal = counter
word = e
return(word)
print(f"{fgv(list)}")
4 Answers 4
One more approach which is doing too much work for your problem, but shows off the stdlib's collections.Counter object which is very useful for a bunch of other applications!
from collections import Counter
words = ['box', 'computer', 'sheep', 'family', 'illegal', 'bubble', 'lamp', 'circuit', 'building', 'plant', 'these', 'cup']
word_counts = [Counter(word) for word in words]
# word_counts is now a list of Counter objects, which each look a little bit
# like {"b": 1, "o": 1, "x": 1} for box
# or {"i": 1, "l": 3, "e": 1, "g": 1, "a": 1} for illegal
# now we'll get the index for the word with the most "i's"
idx_max_by_i = max(enumerate(word_counts), key=lambda pair: pair[1]['i'])[0]
# and convert that back to the word itself by indexing into the words list
result = words[idx_max_by_i]
1 Comment
most_common(n) which show the most common N number of elements, or elements which give back the "exploded" view of the elements in the counter (e.g. Counter('sheep').elements() produces something like "eehps")If you are only interested in one (the first) word that has a most amount of i's in case of a tie, then this functional one-liner may be desirable:
lst = ['box', 'computer', 'sheep', 'family', 'illegal', 'bubble', 'lamp', 'circuit', 'building', 'plant', 'these', 'cup']
print(max(lst, key=lambda x: x.count("i")))
1 Comment
word.count('i') for each word and iterating over the zip of lst and word_counts in your final list compdef count_letter(list):
counter = 0
maximal = 0
word = ""
for e in list:
counter = e.count("i")
if counter > maximal:
maximal = counter
word = e
return word
word_list = ['box', 'computer', 'sheep', 'family', 'illegal', 'bubble', 'lamp', 'circuit', 'building', 'plant', 'these', 'cup']
print(count_letter(word_list))
try this code
4 Comments
If you consider that dictionaries can be keyed on integers then how about:
_list = ['box', 'computer', 'sheep', 'family', 'illegal', 'bubble', 'lamp', 'circuit', 'building', 'plant', 'these', 'cup']
def get_count(list_of_words: list[str], letter: str) -> list[str]|None:
if list_of_words and len(letter) == 1:
d = {}
for word in list_of_words:
d.setdefault(word.count(letter), []).append(word)
return d[max(d)]
print(get_count(_list, 'i'))
Output:
['circuit', 'building']
[w.count('i') for w in list]→[0, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 0]python, strings have acount()method which seems to be what you are looking for,