0

I need help with a function that will take a string and return a dictionary with how many times each letter is in the string using the count() function

For example, for "0010101", it returns a dictionary saying:

The character frequency of "0010101" is {'0': 4, '1': 3}

def character_frequency(string):
  if len(string) == 0:
   return "{}"
# insert loop to determine the character counts in the string here

#test code for reference 
tests = ["", "0010101", "aaabbb"]

for x in tests:
  print('The character frequency of "' + x + '" is', character_frequency(x))

toolic
  • 57,801
  • 17
  • 75
  • 117
saturns
  • 57
  • 6
  • It's a sad day when [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) exists, but one isn't allowed to use it. – 9769953 May 02 '21 at 12:20
  • yea, sadly can't import anything from the collections module :( – saturns May 02 '21 at 12:21
  • I'm afraid you'll need to take a few steps back though, and go through some old stuff. For example, you return `"{}"`, which is a string (containing an opening and closing brace); not a dict as you probably intent to. – 9769953 May 02 '21 at 12:22
  • yea, I'll work on that. Right now my concern is figuring out the main part of the assignment which is returning the dictionary with the character frequencies – saturns May 02 '21 at 12:29
  • Use the `count` function, or `count` *method*? I assume the latter, since I wouldn't know of a standard `count` function. – 9769953 May 02 '21 at 12:38

3 Answers3

0

If you need to use count() function:

def character_frequency(string):
    return {char: string.count(char) for char in set(string)}
Marcin-99
  • 41
  • 2
0

If you are open to a different implementation than count, one way is to use get with a default of 0:

def character_frequency(string):
    freq = {}
    for c in string:
        freq[c] = freq.get(c, 0) + 1
    return freq

#test code for reference 
tests = ["", "0010101", "aaabbb"]

for x in tests:
    print('The character frequency of "' + x + '" is', character_frequency(x))

Output:

The character frequency of "" is {}
The character frequency of "0010101" is {'0': 4, '1': 3}
The character frequency of "aaabbb" is {'a': 3, 'b': 3}
toolic
  • 57,801
  • 17
  • 75
  • 117
0
txt = "I love apples, apple are my favorite fruit"
print(dict(zip(txt,[txt.count(char) for char in txt])))

Count the occurrences of each character in the string and store them as list

Merge the above list with the corresponding characters and convert to dictionary

Marcel.af
  • 73
  • 9