Under Short
Under Short

Reputation: 11

How can I tally the number of times each letter occurred in a string in a list

Word Problem:

Write and test a function that given a string of characters, returns a list with a tally (total number) of each individual character of the alphabet (A through Z) found in the string, ignoring case. The first element in the returned list is the tally for 'A'; the second element is the tally for 'B'; etc.

Function Definition

def countChars(s: str) -> list:

Example Input:

a = 'aBBcccDDDD'
print(countChars(a))

Example Output:

[1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

So far, I created a variable with all of the letters in a alphabet, and empty list for the result, a tally that will count the number occurrences and a variable that will keep track what letter I'm on. I decided to put it in a while loop to loop through every letter in the alphabet (A-Z) and for each letter, I made it so that it will loop through every character in that string. The problem is, my code can't run and I'm not sure if its going to work

def countChars(s: str) -> list:
    tally = 0
    result = []
    alphabet = 1
    letter = 'abcdefghijklmnopqrstuvwxyz'
    while alphabet != 27:
        for i in range(len(s)):
            lower = s.lower()
            if letter[i] in lower[i]:
                tally +=1
                result.append[tally]
            else:
                result.append[0]
        alphabet +=1
    return result

a = 'aBBcccDDDD'
print(countChars(a))

Upvotes: 0

Views: 110

Answers (1)

Sash Sinha
Sash Sinha

Reputation: 22418

You could simplify your loop by utilizing ord():

def count_chars(s: str) -> list[int]:
    counts = [0] * 26
    for ch in s:
        if ch.isalpha():
             counts[ord(ch.lower()) - ord('a')] += 1
    return counts


def main() -> None:
    print(f'{count_chars("aBBcccDDDD") = }')


if __name__ == '__main__':
    main()

Output:

count_chars("aBBcccDDDD") = [1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Upvotes: 0

Related Questions