Being in the IT industry for more than 12 years, I have taken a lot of interviews. And one of the most common and easiest question to break the ice or start with is "Remove duplicate elements from a list". This seems simplest of the question and the expectation is that almost everyone should be able to answer this question. But believe me, not everyone can answer the simplest of the question. This question is mainly for the entry-level tech role but some times even experience d candidate struggles to answer this question.
Without wasting must of time, I can quickly give you one solution and then we will walk through with a variant of the same question.
I am using python 3.8 and collections package to solve this problem.
Q: Return the unique the element of a list.
Import collections
a=[1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,4,5,5]
counter=collections.Counter(a)
print(counter)
print(list(counter.keys()))
Some times the question can be a little different,
Q: find the frequency of each element in the list?
import collections
a=[1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,4,5,5]
counter=collections.Counter(a)
print(counter)
print(f'Frequency of elements in the list{counter.values()}')
Q: Or Which elements repeats the most or least in the list?
import collections
a=[1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,4,5,5]
counter=collections.Counter(a)
print(counter)
print(f'ELement which repeat the most{max(counter,key=counter.get)}')
print(f'ELement which repeat the least{min(counter,key=counter.get)}')
And you can master the collection package of python to answer the simplest of the question. It is one of the most useful packages which helps you solve many problems in your daily programming. One should master this package and it will help you a lot in long run.
Post Comments(0)