在Python 3.x中使用Counter()。找到最小的字符去除以使两个字符串变位
在本文中,我们将学习如何使用counter()
Python3.x中的函数将字符串变成pangram。或更早。为此,我们可以从输入字符串中删除任何字符。我们还将找到要删除的必需字符的数量,以使字符串变成一个字谜。
当两个字符串以任意随机顺序包含相同类型的字母时,它们被称为彼此字母。
counter()方法存在于Python中可用的收集模块中。前提条件是导入collections模块以使用该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
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
结论
在本文中,我们学习了如何通过计算维护anagram关系Python2.x所需的字符数来相互制作两个字符串。需要。