
# A Counter turns a sequence of values into a defaultdict(int)-like 
# object that maps keys to counts (how often the key occurs).
#
# We will primarily use it to create histograms

from collections import Counter

c = Counter([0, 1, 2, 0]) 	# c = { 0:2, 1:1, 2:1 }  (freqs of each key)
print(c)


# #####################################################
# Application:
#
#    Find frequencies of words in documents
# #####################################################

input = [ 'the', 'man', 'owns', 'the', 'hat']

c = Counter(input)
print(c)

# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# This gives us a very simple way to solve our word_counts problem !!
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

# ???????????????????????????????????????????????
# Hey, you get the same with defaultdict(int):
#
# (It's harder because we used a for-loop)
# ???????????????????????????????????????????????

from collections import defaultdict

d = defaultdict(int)

for word in input:
    d[word] += 1
print(d)


# #######################################################################
# Other useful functions in Counter:
# #######################################################################

# Mode:


input = [ 'the', 'man', 'owns', 'the', 'hat', 'the', 'hat', 'the', 'man']

c = Counter(input)
print(c)

print(c.most_common(2))		# List of the 2 most common entries
print(c.most_common(3))		# List of the 3 most common entries

for word, count in c.most_common(2):
   print(f'{word} occurs {count} times')
