How do i count a letter in a word in python?

107 views Asked by At

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

There are 4 answers

4
Anh Dang Vien On BEST ANSWER
def 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

1
juanpethes On

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")))
0
SIGHUP On

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']
1
Adam Smith On

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]