Mike
Mike

Reputation: 53

counting the frequency of a letter in a string

so far this is what i have and this and this will just print out a list with the count of each letter in the string. it only checks for lowercase letters.

`S="""Four score and seven years ago our fathers brought forth on this continent a new nation
Now we are engaged in a great civil war
"""
lowlet = S.lower()
L_count = [0]*26
total_count = 0
alpha = "abcdefghijklmnopqrstuvwxyz"
i = 0
while i < len(lowlet):
    if lowlet[i] in alpha:
        L_count[i][ord(lowlet[i]) - 97] += 1
        total_count += 1
    i += 1
print('total count of letters:',total_count)'

now im giving this algorithm but i cant put it into code and i cant use a for loop i have to use a while loop Initialize a list, L_freq. For each element, count, in L_counts Find the letter corresponding to this count Insert in L_freq, the list: [count, letter]

Upvotes: 0

Views: 564

Answers (1)

corvid
corvid

Reputation: 11197

is it a requirement that it be a list? I feel like a dictionary would be easier to handle

sentence = s.lower()
counts = { letter: sentence.count(letter) for letter in alpha }
print(counts)

this will print like: {'a': 5, 'b': 2}

Upvotes: 0

Related Questions