Reputation: 9
This question was a part of the the interview process and I couldn't figure it out.
Given a list of integers, create a histogram where the output is a dictionary. The key are the elements in the list and the values are the count of elements in the list.
For example, inputlist: [2,3,4,2,5,7,3,2,4]
and expected output: {2:3,3:2,4:2..}
I know there has to be a loop iterating over the list and then inserting those values in the dictionary. But I messed up on the syntax bad. Would appreciate if somebody could guide me with syntax or pseudocode. HELP!
Upvotes: 0
Views: 940
Reputation: 116
This would be my solution using dictionary comprehension:
inputlist = [2,3,4,2,5,7,3,2,4]
result = {k:inputlist.count(k) for k in set(inputlist)}
However I agree that Counter
from collections
would probably perform better as the inputlist
would get bigger (see list.count() vs Counter() performance)
Upvotes: 2
Reputation: 749
Try this:
from collections import Counter
inputlist = [2,3,4,2,5,7,3,2,4]
freq_counter = Counter(inputlist)
print(freq_counter)
Upvotes: 1
Reputation: 1166
For future reference you can't just provide the question, you need to provide a minimum reproducible example.
Here's the answer anyways:
output = {}
inputlist = [2,3,4,2,5,7,3,2,4]
for num in inputlist:
if num in output:
output[num] += 1
else:
output[num] = 1
print(output)
Upvotes: 1