In: Computer Science
Program 1:
l=[1,1,1,1,1,2,2,2,2,3,3,3,4,5,6]
#In the above list the most three occurrences are 1,2,3 and least
three occurrences are 4,5,6
d=dict()
for i in l:
d[i]=0
for i in l:#for each element in list
d[i]+=1#increment count value in dictionary
#sort the dictionary by value and get the results
l=sorted(d.items())#obtain the list of tuples
l.sort(key=lambda i:i[1])#sort the list based on second field in
ascending order
print("The least three occuring elements are :")
for i in range(3):
print(l[i][0])
l.sort(key=lambda i:i[1],reverse=True)#sort the list based on
second field in descending order
print("The most three occuring elements are :")
for i in range(3):
print(l[i][0])
Program 2:
d={1:"word1",3:"temp",2:"value3"}
#sorting by key
print("Sorting by Key in ascending order")
temp=(sorted(d.items()))
for i in temp:
print(i[0],"=>",i[1])#print after Sorting
print("Sorting by Value in asscending order")
#Sorting by value
l=[]
for k,v in d.items():
l.append((k,v))#append the tuples to list
l.sort(key=lambda i:i[1])#sort using second element of tuple
which is value of dict
for i in l:
print(i[0],"=>",i[1])#print after Sorting