´╗┐Python-courses-python-exercises-Python-courses- built-inintegrated/DOS-python-module

Exercise 51

Write a Python algorithm as a function which takes a list L as a parameter and which returns the list of elements duplicated at least 3 times without using neither the count() method nor any predefined method in Python. (you can use exercise 23)

Solution

# function which determines the number of occurrences of a character in a list
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

# function which determines the list of elements duplicated at least 3 times
def duplicate3 (L):
#initialization of the list of duplicate elements
ldup = []
for x in L:
if (numberOccurrence (L, x) >= 3 and x not in ldup):
ldup.append (x)
return ldup

#Example
L = [5, 7, 23, 5, 23, 7, 5, 19, 23, 4, 7, 29, 7]
print (duplicate3 (L)) # the output: [5, 7, 23]
Younes Derfoufi
my-courses.net

Leave a Reply