[Algorithm]Python frequency count algorithm

Error Coder·2022년 10월 10일
0

자료구조&알고리즘

목록 보기
5/10

Given an unsorted list of some elements(may or may not be integers), Find the frequency of each distinct element in the list using a dictionary
(일부 요소의 정렬되지 않은 목록(정수일 수도 있고 아닐 수도 있음)이 주어지면 딕셔너리를 사용하여 목록에서 각 개별 요소의 빈도를 찾습니다.)

Example:

Input : `
``
[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]

Output :
`
``
 1 : 5
         2 : 4
         3 : 3
         4 : 3
         5 : 2

Explanation : Here 1 occurs 5 times, 2
occurs 4 times and so on...

The problem can be solved in many ways. A simple approach would be to iterate over the list and use each distinct element of the list as a key of the dictionary and store the corresponding count of that key as values. Below is the Python code for this approach:
(문제는 많은 방법으로 해결될 수 있습니다. 간단한 접근 방식은 목록에 대해 반복하고 사전의 키로 목록의 각 개별 요소를 사용하고 해당 키의 개수를 값으로 저장하는 것입니다. 아래는 이 접근 방식을 위한 파이썬 코드입니다.)

# Python program to count the frequency of
# elements in a list using a dictionary

def CountFrequency(my_list):

	# Creating an empty dictionary
	freq = {}
	for item in my_list:
		if (item in freq):
			freq[item] += 1
		else:
			freq[item] = 1

	for key, value in freq.items():
		print ("% d : % d"%(key, value))

# Driver function
if __name__ == "__main__":
	my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]

	CountFrequency(my_list)

OutPut:

 1 :  5
 2 :  4
 3 :  3
 4 :  3
 5 :  2

Time Complexity:O(N), where N is the length of the list.
Alternative way: An alternative approach can be to use the list.count() method.
(시간 복잡성:O(N), 여기서 N은 목록의 길이입니다.
다른 방법: 다른 접근 방식은 list.count() 메서드를 사용하는 것입니다.)

# Python program to count the frequency of
# elements in a list using a dictionary

def CountFrequency(my_list):
	
	# Creating an empty dictionary
	freq = {}
	for items in my_list:
		freq[items] = my_list.count(items)
	
	for key, value in freq.items():
		print ("% d : % d"%(key, value))

# Driver function
if __name__ == "__main__":
	my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
	CountFrequency(my_list)

Output:

 1 :  5
 2 :  4
 3 :  3
 4 :  3
 5 :  2

Time Complexity:O(N2), where N is the length of the list. The time complexity list.count() is O(N) alone, and when used inside loop it will become O(N2).

Alternative way:An alternative approach can be to use the dict.get() method. This makes the program much more shorter and makes understand how get method is useful instead of if…else.

(시간 복잡성:O(N2) 여기서 N은 목록의 길이입니다. 시간 복잡도 리스트.count()는 O(N) 단독이며, 루프 내에서 사용될 경우 O(N2)가 된다.

다른 방법:다른 접근 방식은 dict.get() 메서드를 사용하는 것입니다. 이렇게 하면 프로그램이 훨씬 더 짧아지고 get method가 if… else 대신 어떻게 유용한지 이해할 수 있습니다.)

# Python program to count the frequency of
# elements in a list using a dictionary

def CountFrequency(my_list):
	
# Creating an empty dictionary
count = {}
for i in [1, 1, 1, 5, 5, 3, 1, 3, 3, 1 ,4, 4, 4, 2, 2, 2, 2]:
	count[i] = count.get(i, 0) + 1
return count

# Driver function
if __name__ == "__main__":
	my_list =[1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]
	print(CountFrequency(my_list))

Output:

{1: 5, 5: 2, 3: 3, 4: 3, 2: 4}
profile
개발자 지망생

0개의 댓글