## Friday, November 6, 2020

Solution Exercise 81: Python algorithm to find the number of occurrences of all word in given string text #### Exercise 81

Write a Python algorithm as function which takes as parameter a string s and that return the dictionary whose keys are the words that making up the string s and whose values are the number of occurrences of words within the string Text s. Example: if s = "I use Python for datascience but I don't use Python for mobile", the algorithm returns the dictionary:
``d = {'I': 2, 'use': 2, 'Python': 2, 'for': 2, 'datascience': 1, 'but': 1, "don't": 1, 'mobile': 1}``

#### Solution

``````def wordOccurrence(s):

# initializing the dictionary that we want to obtain
d = dict({})

# convrting the the string s into a list
listWords = s.split()

# iterate over all word in listWords
# and adding the number of occurrences of all word to the dictionary d
for word in listWords:
d[word] = listWords.count(word)

return d

# Example
s = "I use Python for datascience but I don't use Python for mobile"
print(wordOccurrence(s))
# the output is :
#{'I': 2, 'use': 2, 'Python': 2, 'for': 2, 'datascience': 1, 'but': 1, "don't": 1, 'mobile': 1}``````

Younes Derfoufi
my-courses.net

## Python Exercises With Solutions

1. Python Arithmetic Exercises
2. Equations & System Of Equations
3. Polynomials and Functions
4. Python Arithmetic Exercises
5. Numpy, Matplolib, Sympy , Scipy - Exercises
6. Python Arithmetic Exercises

Younes Derfoufi

## Sample Text 