xxxxxxxxxx
def count_frequency(numbers):
frequency = {}
for num in numbers:
if num in frequency:
frequency[num] += 1
else:
frequency[num] = 1
return frequency
numbers = [1, 2, 2, 3, 1, 4, 2, 4, 5]
frequency = count_frequency(numbers)
print("Frequency:", frequency)
xxxxxxxxxx
# easiest way to count the frequency of all elements in a list
lst = ['Sam', 'Sam', 'Tim', 'Tim', 'Tim', 'r', 'l']
freq = {} # stores the frequency of elements
counting = [freq.update({x: lst.count(x)}) for x in lst]
# output of freq
{'Sam': 2, 'Tim': 3, 'r': 1, 'l': 1}
#credit: buggyprogrammer.com
#Note: if you print "counting" it will return a list full of None so ignore it.
xxxxxxxxxx
from collections import Counter
list1=['apple','egg','apple','banana','egg','apple']
counts = Counter(list1)
print(counts)
# Counter({'apple': 3, 'egg': 2, 'banana': 1})
xxxxxxxxxx
import collections
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
counter=collections.Counter(a)
print(counter)
# Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1})
print(counter.values())
# [4, 4, 2, 1, 2]
print(counter.keys())
# [1, 2, 3, 4, 5]
print(counter.most_common(3))
# [(1, 4), (2, 4), (3, 2)]
xxxxxxxxxx
from collections import Counter
def frequency_table(n):
table = Counter(n)
print('Number\tFrequency')
for number in table.most_common() :
print('{0}\t{1}'.format(number[0], number[1]))
# src : Doing Math With Python
xxxxxxxxxx
def countFreq(arr):
visited = [False for _ in range(len(arr))]
for i in range(len(arr)):
count = 1
if visited[i]:
continue
for j in range(i+1, len(arr)):
if arr[i] == arr[j]:
count += 1
visited[j] = True
visited[i] = True
print(f'{arr[i]} : {count}')
# Time complexity: O(n * n)
# space complexity: O(n)
xxxxxxxxxx
list1=list(input("Enter list:"))
length_list1=len(list1)
uniq=[]
dupl=[]
count = i = 0
while i < length_list1:
element=list1[i]
count=1
if element not in uniq and element not in dupl:
i += 1
for j in range(i, length_list1):
if element == list1[j]:
count += 1
else:
print("Element", element, "frequency", count)
if count == 1:
uniq.append(element)
else:
dupl.append(element)
else:
i += 1