´╗┐Python-courses-python-exercises-python--Python-courses-configure script-run-script

Exercise 23

Write an algorithm in python that returns the number of occurrences of an 'a' element in a given list L without using any predefined functions in Python. Example if L = [7, 23, 5, 23, 7, 19, 23, 12, 29] and a = 23, the algorithm returns 3.

Solution

#coding: utf-8
def numberOccurrence (L, a):
# initialize the number of occurrences of a in L
numberOcc = 0
for x in L:
if x == a:
numberOcc = numberOcc + 1
return numberOcc
#Example
L = [7, 23, 5, 23, 7, 19, 23, 12, 29]
a = 23
print ("the number of occurrences of a in L is:", numberOccurrence (L, a))
# The output is: the number of occurrences of a in L is: 3

Younes Derfoufi
my-courses.net

Leave a Reply