Home > Mobile >  Counting recurring letters in a string with python
Counting recurring letters in a string with python

Time:12-10

word = 'monsoon'

def check(x):
    emptyList = []
    search = list(word)
    for element in x:
        count_elements = str(search.count(element))
        emptyList  = count_elements
        
    print(emptyList)

check(word)

I am trying to count all the occurrences of each letter in the word and return it in a list, however I get ['1', '3', '2', '1', '3', '3', '2'] which kind of works but I want to avoid counting the same letter twice so I should have ['1', '3', '2', '1'] as the answer, how can I go about this?

CodePudding user response:

You can use dictionary object for that:

word = 'monsoon'

def check(x):
   count = {letter:x.count(letter) for letter in x}
   print(count)

check(word)

Dictionary in python saves values as key:value pairs and does not allow duplicate keys.

CodePudding user response:

If you don't want to modify your existing code much, you can iterate over a set of the elements in your word which means each one will only be counted once

word = 'monsoon'

def check(x):
    emptyList = []
    search = list(word)
    for element in set(x):
        count_elements = str(search.count(element))
        emptyList  = count_elements
        
    print(emptyList)

check(word)

gives

['2', '3', '1', '1']

Note that the order is not preserved since sets are unordered so you may want to return a different data structure if that's important

  • Related