使用Python 3.x 中的Counter()函式查詢使兩個字串變為異位詞所需移除的最小字元數


在本文中,我們將學習如何使用Python 3.x(或更早版本)中的counter()函式將字串轉換為Pangram(包含所有26個英文字母的句子)。為此,我們允許從輸入字串中刪除任何字元。我們還將找到需要移除的字元數量,以使字串成為異位詞。

當兩個字串包含相同型別的字母,但順序不同時,它們被稱為彼此的異位詞。

counter()方法存在於Python中可用的collections模組中。使用counter()函式的先決條件是匯入collections模組。

演算法

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

collections.Counter是字典的子類,用於確保直譯器自動計數字母。我們實際上不需要手動建立子字串或檢查它們是否為異位詞。

示例

即時演示

# 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. 也需要。

更新於:2019年8月29日

瀏覽量:138

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.