Reputation: 41
You are given an array of numbers. Print the least occurring element. If there is more than 1 element print all of them in decreasing order of their value.
Input:
[9, 1, 6, 4, 56, 56, 56, 6, 4, 2]
Output:
[9, 2, 1]
I actually got output but doesn't execute private cases, please help me.
from collections import Counter
n=int(input())
ans=""
list1=[]
list2=[]
list1=[int(x) for x in input().strip().split()][:n]
dict1=dict(Counter(list1))
k=min(dict1,key=dict1.get)
l=dict1[k]
for i,j in dict1.items():
if(j==l):
list2.append(i)
list2.reverse()
for i in list2:
ans+=str(i)+' '
print(ans[:-1])
Upvotes: 3
Views: 2500
Reputation: 297
We do not need to use a list comprehension Counter has a built in method most_common() which lists all of the counts in order from greatest to least common - we can just reverse this. :
from collections import Counter
c = Counter([9,9,9,1,1,2,2,2,3,3,3,3,4,4,1,1,0])
d = sorted(c.most_common(), key = lambda i: i[1])
# Items are now in an ordered list of tuples from least to most
print(d)
print(d[0][0])
Output:
[(0, 1), (4, 2), (9, 3), (2, 3), (1, 4), (3, 4)]
0
Upvotes: 0
Reputation: 26
You can do this by simply sorting the list before reversing it. and you need not create a string for list . simply *list_name and it will print list using spaces.
from collections import Counter
n=int(input())
list1=[]
list2=[]
list1=[int(x) for x in input().strip().split()][:n]
dict1=dict(Counter(list1))
k=min(dict1,key=dict1.get)
l=dict1[k]
for i,j in dict1.items():
if(j==l):
list2.append(i)
list2.sort(reverse=True)
print(*list2)
Upvotes: 0
Reputation: 375
I see a lot of complicated answers. It can actually be done by just using list comprehension over the items in the instance of Counter()
:
>>> from collections import Counter
>>> count = Counter([9, 1, 6, 4, 56, 56, 56, 6, 4, 2])
>>> values = [key for key, value in count.items() if value == min(count.values())]
>>> values.sort(reverse=True) # [9, 2, 1]
Upvotes: 0
Reputation: 274
Without any import you can also try
def getAllindex(lst, elem):
return list(filter(lambda a: lst[a] == elem, range(0,len(lst))))
lst = [9, 1, 6, 4, 56, 56, 56, 6, 4, 2]
list_count = [lst.count(xx) for xx in lst]
idx = getAllindex(list_count, min(list_count))
l = list(set([lst[ii] for ii in idx]))
l.sort(reverse = True)
print(l)
Output
[9, 2, 1]
Upvotes: -1
Reputation: 154
The reason you are getting error is because Counter/Dictionary is an unordered collection. So your list2 could have elements in a different order each time you run it. Try running your code for [9, 1, 6, 4, 56, 6, 4, 2] input.
from collections import Counter
n=int(input())
list1=[]
list2=[]
list1=[int(x) for x in input().strip().split()][:n]
dict1=dict(Counter(list1))
k=min(dict1,key=dict1.get)
l=dict1[k]
for i,j in dict1.items():
if(j==l):
list2.append(i)
list2.sort(reverse=True)
print(' '.join(str(i) for i in list2))
Upvotes: 0