
Untitled
By: a guest on
Jun 9th, 2012 | syntax:
Python | size: 1.75 KB | hits: 26 | expires: Never
"""
Data una lista l di interi, si vuole modificarla cancellando tutti gli elementi i cui valori compaiono esattamente una volta, mantenendo lo stesso ordine che gli elementi avevano inizialmente. (p.e. se l'ingresso e' l = [6, 1, 6, 1, 4, 1, 1, 3, 5] allora il risultato e' L = [6, 1, 6, 1, 1, 1]). Si scriva una procedura utilizzando gli operatori per le liste visti lezione.
"""
# returns the number of occurrences of element e in list l
def get_occurrences (l, e):
count = 0
for x in l:
if x == e: count += 1
return count
# remove elements according to exam question
# complexity: O(n^2)
def fun1 (l):
lc = list(l) # copy of the input list (is this really needed? we can re-use the same list for occurrences count)
i = 0 # pointer to the first element of the list l
while i < len(l):
occurrences = get_occurrences(lc, l[i]) # get number of occurrences of current element
if occurrences == 1: del(l[i]) # if it appears only one time in the list delete it
else: i += 1 # consider the next element otherwise
return l
# remove elements according to exam question
# complexity: O(n)
def fun2 (l):
d = dict() # create an empty dictionary (hash table)
# for each element in input list
for e in l:
if d.has_key(e): d[e] += 1 # if this element has been already added to the dictonary increment the related number
else: d[e] = 1 # set up the related number of this element to 1 (occurrence) otherwise
# return the list in which all elements that appears only one time have been deleted
return [ e for e in l if d[e] > 1 ]
# like fun1 but much more simple!
# complexity: O(n^2)
def fun3 (l):
return [ e for e in l if l.count(e) > 1 ]
# main
l = [6, 1, 6, 1, 4, 1, 1, 3, 5]
print fun1(l)
print fun2(l)
print fun3(l)