Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python 3.x에서 Counter() 사용하기. 두 개의 문자열을 아나그램으로 만들기 위한 최소 문자 제거 찾기

<시간/>

이 기사에서는 Python 3.x에서 counter() 함수를 사용하여 문자열을 팬그램으로 만드는 방법을 배웁니다. 또는 더 일찍. 그렇게 하려면 입력 문자열에서 모든 문자를 제거할 수 있습니다. 또한 문자열을 아나그램으로 만들기 위해 제거해야 하는 필수 문자의 수를 찾습니다.

두 문자열이 임의의 순서로 동일한 유형의 알파벳을 포함하는 경우 서로의 아나그램이라고 합니다.

counter() 메서드는 Python에서 사용할 수 있는 컬렉션 모듈에 있습니다. 전제 조건은 counter() 함수를 사용하기 위해 컬렉션 모듈을 가져오는 것입니다.

알고리즘

1. Conversion of input string into a dictionary type having characters as
keys and their frequency as values using Counter(inp_str) available in
the collections module.
2. Counting the total number of keys and counting the number of keys in
common to both dictionaries converted from input strings.
3. If no common keys are detected this means there is a need for removal
of (sum of the length of both dictionaries) characters from both the
input strings.
4. otherwise (max(length of both dictionaries) – number of Common keys
available ) will give the required number of characters to be removed

컬렉션.카운터 인터프리터가 문자를 자동으로 계산하도록 하는 사전 하위 클래스입니다. 실제로 부분 문자열을 생성하거나 수동으로 아나그램인지 확인할 필요가 없습니다.

예시

# two strings become anagram
from collections import Counter
def convertAnagram(str_1, str_2):
   # conversion of strings to dictionary type
   dict_1 = Counter(str_1)
   dict_2 = Counter(str_2)
   keys_1 = dict_1.keys()
   keys_2 = dict_2.keys()
   # count number of keys in both lists of keys
   count_1 = len(keys_1)
   count_2 = len(keys_2)
   # convert pair of keys into set to find common keys
   set_1 = set(keys_1)
   commonKeys = len(set_1.intersection(keys_2))
   if (commonKeys == 0): # no common things found i.e. all are distinct
      return (count_1 + count_2)
   else: # some elements are already matching in input
      return (max(count_1, count_2)-commonKeys)
str_1 ='Tutorials'
str_2 ='sTutalori'
str_3='Point'
print (convertAnagram(str_1, str_2))
print (convertAnagram(str_3, str_2))

출력

0
6

결론

이 기사에서 우리는 아나그램 관계 Python 2.x를 유지하는 데 필요한 문자 수를 계산하여 서로의 두 문자열 아나그램을 만드는 방법을 배웠습니다. 필요합니다.