使用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.