Last Updated on February 12, 2024

The goal for this lab was to count the number of times a specific letter shows up in a given string. 

This is what they started me out with:

def countA(text):
    count = 0
    for c in text:
        if c == 'a':
            count = count + 1
    return count

print(countA("banana"))

And its alternative:

def countA(text):

    return text.count("a")

I decided that the second one would be a simpler one to use in this case.

This actually ended up being a lot easier than I expected. Here is my initial code:

def countAll(text):
    wordDict = {}
    
    for char in text:
        if char not in wordDict:
            wordDict[char] = text.count(char)
    
    return wordDict
            

print(countAll("banana"))
print(countAll("curly fries"))

Result:

However, the instructions just asked for letters, not all characters, so I needed to add in a condition that checked if the character was a letter before adding it to the dictionary. Here is the final code for that:

def countAll(text):
    wordDict = {}
    
    for char in text:
        if char not in wordDict and char.isalpha():
            wordDict[char] = text.count(char)
    
    return wordDict
            

print(countAll("banana"))
print(countAll("curly fries 123!"))

The next lab builds on this one so be sure to check that one out.

Leave a Reply

Your email address will not be published. Required fields are marked *

nine + 16 =