6

Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters("This is a sentence.") should return {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}

def count_letters(text):
      result = {}
      # Go through each letter in the text
      for letter in text:
        # Check if the letter needs to be counted or not
        if letter not in result:
          result[letter.lower()] = 1
        # Add or increment the value in the dictionary
        else:
          result[letter.lower()] += 1
      return result

    print(count_letters("AaBbCc"))
    # Should be {'a': 2, 'b': 2, 'c': 2}

    print(count_letters("Math is fun! 2+2=4"))
    # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

    print(count_letters("This is a sentence."))
    # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
AMC
  • 2,642
  • 7
  • 13
  • 35
Yahia Naeem
  • 63
  • 1
  • 2
  • 7

23 Answers23

8
def count_letters(text):
  result = {}
  text = text.lower()
  # Go through each letter in the text
  for letter in text:
   
    # Check if the letter needs to be counted or not
    if letter.isalpha() :
      # Add or increment the value in the dictionary
      count = text.count(letter)
      result[letter] = count
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
7

This should work:

>>> from collections import Counter
>>> from string import ascii_letters
>>> def count_letters(s) :
...     filtered = [c for c in s.lower() if c in ascii_letters]
...     return Counter(filtered)
... 
>>> count_letters('Math is fun! 2+2=4')
Counter({'a': 1, 'f': 1, 'i': 1, 'h': 1, 'm': 1, 'n': 1, 's': 1, 'u': 1, 't': 1})
>>> 
lenik
  • 23,228
  • 4
  • 34
  • 43
1

So I got your question,

def count_letters(text):
  result = {}
  text = text.lower()
  # Go through each letter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    if letter in "abcdefghijklmnopqrstuvwxyz":
      #
      if letter not in result:
        result[letter] = 1
      # Add or increment the value in the dictionary
      else:
        result[letter] += 1
  return result

  print(count_letters("AaBbCc"))

  # Should be {'a': 2, 'b': 2, 'c': 2}

  print(count_letters("Math is fun! 2+2=4"))
  # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 
  1, 'n': 1}

  print(count_letters("This is a sentence."))
  # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 
  1}
1
def count_letters(text):
  result = {}
  for letter in text:
    #check if it alphabet or something else
    # Check if the letter needs to be counted or not
    if letter.isalpha():
      result[letter.lower()]=result.get(letter.lower(),0)+1
    # Add or increment the value in the dictionary
  return result
print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}
print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}
print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Rushabh
  • 11
  • 1
1
def count_letters(text):
  result = {}
  # Go through each letter in the text
  text=text.lower()
  for letter in text:
    if letter in 'abcdefghijklmnopqrtsuvwxyz':

      if letter in result:
        result[letter]+=1
      
      else:
        result[letter]=1
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
1

The ".isalpha()" method comes in very handy. See how I solved it:

def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    
    if letter.isalpha() and letter not in result:
      letter=letter.lower()
      result[letter]=1
    elif letter.isalpha()==False:
      pass
    else:
      result[letter]+=1

    ___
    # Add or increment the value in the dictionary
    ___
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
Nigel Iyke
  • 21
  • 3
1

you can use the .isalpha() method to check if the character is an alphabet letter.

Then use the .get method to return the value from a specific key.

def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text.lower():
    # Check if the letter needs to be counted or not
    if(letter.isalpha()):
      result[letter] = result.get(letter,0)+1
    # Add or increment the value in the dictionary
    
  return result
1

if letter.isalpha() and letter != " ": checks if the letter is only a letter, not a number, a punctuation or a blank space.

def count_letters(text):
  result = {}
  # Go through each letter in the text
  text_lower=text.lower()
  # Go through each letter in the text
  for letter in text_lower:
    # Check if the letter needs to be counted or not
    if letter.isalpha() and letter != " ":
      if letter not in result:
        result[letter] = 0  
    # Add or increment the value in the dictionary
      result[letter] += 1
  return result
0
def count_letters(text):
 r = {}
  # Go through each letter in the text
 for letter in text:
    # Check if the letter needs to be counted or not
     for letter in text:
# Check if the letter needs to be counted or not
 for alp in letter:
  # To check the letters are alphabets or not
  if alp in ascii_letters:
   #Converting into lowercase as python is case sensitive
    if alp.lower() in r and alp!=' ':
      r[alp.lower()]+=1
    elif alp.lower() not in r and alp!=' ':
      r[alp.lower()]=1
  # Add or increment the value in the dictionary
  return r

print(count_letters("AaBbCc"))
print(count_letters("Math is fun! 2+2=4"))
print(count_letters("This is a sentence."))
  • Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it works better than what the OP provided. – ChrisGPT was on strike May 07 '20 at 19:29
  • Also, please _never_ use single-space indentation. It is very hard to read, and in a language like Python where whitespace is significant it's _insane_. – ChrisGPT was on strike May 07 '20 at 19:30
0
def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    if (letter.lower() not in result ) :
      if not letter.isalpha():
        continue
      result[letter.lower()] = 0
             # Add or increment the value in the dictionary
    result[letter.lower()] += 1
    continue
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
0
def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text.lower():
    # Check if the letter needs to be counted or not
    if letter.isalpha() and letter not in result:
    # Add or increment the value in the dictionary
      result[letter] = text.lower().count(letter) 
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
0
def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    if letter.isalpha():
      result[letter.lower()]=result.get(letter.lower(),0)+1
    # Add or increment the value in the dictionary
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
apayziev
  • 3
  • 5
Rushabh
  • 11
  • 1
0
def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    if letter.isalpha():
      if letter not in result:
        result[letter.lower()] = 1
      else:
        result[letter.lower()] +=1
    # Add or increment the value in the dictionary
    
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
abdala
  • 1
  • 1
    Please take a look at the following post which explains how to properly format code blocks https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks – NotAName Jun 02 '20 at 23:54
  • Can you include inline code span so the code is readable & verifiable. – Usama Abdulrehman Jun 03 '20 at 01:16
0

Well, in the second comment it says that you should : # Check if the letter needs to be counted or not

You did not check this. You checked only if the letter is in your dictionary named 'result', which is needed to add characters that don't exist already in the new dictionary. In this case, your program takes a blank space as a "letter". If we were to change the 'letter' variable as 'element', things would be more clear.

if letter.isalpha() == True:

You should use the above line to check only for the letters. For each element of the input text, this block would be skipped when the a non-letter character is met(blank space, number of special character).

All in all, your script should look like this:

def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    if letter.isalpha() == True:
      if letter.lower() not in result:
        result[letter.lower()] = 1
    # Add or increment the value in the dictionary
      else:
        result[letter.lower()] += 1
    
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
0

This is what i did

def count_letters(text):
    result = {}
  # Go through each letter in the text
    text=text.lower()
    for letter in text:
    # Check if the letter needs to be counted or not
        if letter.isalpha():
    # Add or increment the value in the dictionary
            result[letter] = result.get(letter,0) + 1
        else:
            pass
    return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}
print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}
print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
0
def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    if type(letter)==str:
    # Add or increment the value in the dictionary
     if letter not in result:
       result[letter.lower()]=1
     else:
        result[letter.lower()]+=1


    
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
Yann
  • 2,426
  • 1
  • 16
  • 33
Matin Najafi
  • 95
  • 2
  • 12
0
def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text.lower():
    # Check if the letter needs to be counted or not
    if letter.isalpha() and letter not in result:
    # Add or increment the value in the dictionary
      result[letter] = text.count(letter)
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
0
    def count_letters(text):
  result = {}
  # Go through each letter in the text
  text=text.casefold()
  for letter in text:
    # Check if the letter needs to be counted or not
    if (letter.isalpha()): 

    # Add or increment the value in the dictionary
      result.update({letter:text.count(letter)})
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
Shay
  • 1
0
def count_letters(text):
  result = {}
  for letter in text.lower():
    if letter.isalpha():
      lettercount = text.lower().count(letter)
      result[letter] = lettercount
  return result
0
def count_letters(text):
    result = {}
    text = text.lower().replace(" ","")
    text = text.replace("", " ").split()
    dummy = []
    dummy1 = ""

    for x in text: # remove non-letter
        if x.isalpha():
            dummy.append(x)
            dummy1 = "".join(dummy)

    for letter in dummy1:
        if letter not in result:
            result[letter] = 0
        result[letter] += 1
    return result

print(count_letters("AaBbCc"))
print(count_letters("Math is fun! 2+2=4"))
print(count_letters("This is a sentence."))
Alex
  • 13
  • 2
0
def  count_letters(text):
    result = {}
    for letter in text.lower():
        if letter == " " or letter.isalpha() == False:
            continue:
        if letter not in result:
            result[letter] = 0
        result[letter] += 1
    return result
  • 3
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 09 '21 at 09:40
  • `letter.isalpha()` already handles the whitespace check (`" ".isalpha()` is `False`) – Gino Mempin Oct 09 '21 at 11:07
0
def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text.lower():
    # Check if the letter needs to be counted or not
     if letter.isalpha() and letter not in result:
       result[letter] = text.lower().count(letter)
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
apayziev
  • 3
  • 5
0
def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    if letter .isalpha() and letter not in result:
    # Add or increment the value in the dictionary
      result[letter.lower()]=text.lower().count(letter)
  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

print(count_letters("This is a sentence."))
# Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
  • I ran your code and getting this output: ```>>> print(count_letters("AaBbCc")) {'a': 0, 'b': 0, 'c': 0} >>> print(count_letters("Math is fun! 2+2=4")) {'m': 0, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1} >>> print(count_letters("This is a sentence.")) {'t': 0, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}``` – user11717481 Feb 25 '22 at 23:42