Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (45.3k points)

This is a question from pyschools.

I did get it right, but I'm guessing that there would be a simpler method. Is this the simplest way to do this?

def countLetters(word):

    letterdict={}

    for letter in word:

        letterdict[letter] = 0

    for letter in word:

        letterdict[letter] += 1

    return letterdict

This should look something like this:

>>> countLetters('google')

{'e': 1, 'g': 2, 'l': 1, 'o': 2}

1 Answer

0 votes
by (16.8k points)

Here is another optimized way to do it:

>>> import collections

>>> print collections.Counter("google")

Counter({'o': 2, 'g': 2, 'e': 1, 'l': 1})

Hope it helps!

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.6k points)

Browse Categories

...