## Tuesday, December 8, 2020

Solution exercise 93: python algorithm which determines a dictionary of occurrences in a string #### Exercise 93

1 - Write a function named count_characters() which accepts a character string and which returns the occurrence of the characters contained in the string in the form of a dictionary.
2 - Write a function named count_words() which accepts a character string and which returns the occurrence of the words contained in the string as a dictionary.

#### Solution

Question 1
``````def count_characters(s):
d = dict ({})
listUnique = []
for c in s:
if c not in listUnique and c!= ' ':
listUnique.append (c)
d [c] = s.count (c)

return d
# Example
s = "Python Programming"
print (count_characters(s))
# The output is:
# {'P': 2, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 2, 'r': 2, 'g': 2, 'a': 1, 'm': 2, 'i': 1}``````
Question 2
``````def count_words (s):
d = dict ({})
listUnique = []
listWords = s.split()
for word in listWords:
if word not in listUnique:
listUnique.append(word)
d[word] = listWords.count(word)

return d
# Example
s = "Python is programming language and is the most used language"
print (count_words(s))
# The output is:
{'Python': 1, 'is': 2, 'programming': 1, 'language': 2, 'and': 1, 'the': 1, 'most': 1, 'used': 1}``````

Younes Derfoufi
my-courses.net 