Exercise 79
Write using the count() method, a python algorithm as a function which takes as parameter a list of integers L and which returns without repetitions the list of tuples (n, occ_n) formed by the elements n of L and their occurrence occ_n. Example: if
L = [22, 7, 14, 22, 7, 14, 7, 14, 11, 7],
the algorithm returns the list
[(22, 2), (7, 4), (14, 3 ), (22, 1), (11, 1)]
Solution
def tuples_items_occ (L):
# initialization of the list of tuples (n, occ_n)
listItemsOcc = []
for x in L:
if (x, L.count (x)) not in listItemsOcc:
listItemsOcc.append ((x, L.count (x)))
return listItemsOcc
# Example
L = [22, 7, 14, 22, 7, 14, 7, 14, 11, 7]
print (tuples_items_occ (L))
#The output of the program is:
# [(22, 2), (7, 4), (14, 3), (11, 1)]
Younes Derfoufi
my-courses.net
my-courses.net