Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Letter Count Dictionary

My homework problem is to write a Python function called LetterCount() which takes a string as an argument and returns a dictionary of letter counts. However, my code includes white space and commas as a part of the dictionary which i don't want. Can you please help me out. How do i remove the white space from my list? Here is my code?

import string
def LetterCount(str):
    str= str.lower().strip()
    str = str.strip(string.punctuation)
    list1=list(str)
    lcDict= {}
    for l in list1:
        if l in lcDict:
            lcDict[l] +=1
        else:
            lcDict[l]= 1
    print lcDict

LetterCount("Abracadabra, Monsignor")
like image 547
Ivan Avatar asked Dec 17 '22 15:12

Ivan


1 Answers

For the letter count, the best way is to use the dictionary.

s = "string is an immutable object"
def letter_count(s):
    d = {}
    for i in s:
        d[i] = d.get(i,0)+1
    return d

Output:

{'a': 2, ' ': 4, 'c': 1, 'b': 2, 'e': 2, 'g': 1, 'i': 3, 'j': 1, 'm': 2, 'l': 1, 'o': 1, 'n': 2, 's': 2, 'r': 1, 'u': 1, 't': 3}
like image 170
Dry_accountant_09 Avatar answered Dec 29 '22 14:12

Dry_accountant_09