given an array print least frequent elements

Viewed 1433

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])
4 Answers

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]

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))

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)

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]
Related