使用collections.Counter()在Python程序中进行字谜检查
如果两个字符串具有相同的字符(即使顺序不同),也可以说是每个字母的变位符号。在本教程中,我们将使用collections.Counter()方法检查Python中的字谜。
Input: string_one = "cat" string_two = "tac" Ouput: True
collections.Counter()
collection.Counter()返回一个字典,其中包含字符串中每个字符的频率。计数器对象有不同的方法来查找最常见的元素,唯一元素,计数等。
让我们看一个例子。
示例
# importing the collections module
import collections
# creating Counter object
counter = collections.Counter("Hafeez")
# printing the counter
print(counter)
# displaying most common character from the string
print("\nMost common character")
print(counter.most_common(1))输出结果
如果运行上面的程序,您将得到以下结果。
Counter({'e': 2, 'H': 1, 'a': 1, 'f': 1, 'z': 1})
Most common character
[('e', 2)]检查字谜的步骤。
算法
1. Initialise two strings. 2. Create collections.Counter() objects for both strings. 3. If both of the objects are equal. 3.1. Print True 4. Else print False
让我们看一个例子。
示例
# importing the collections module import collections # initializing strings string_one = "cat" string_two = "atc" # checking the Counter objects of both strings if collections.Counter(string_one) == collections.Counter(string_two): # they are equal so, printing True print(True) else: # they are not equal so, printing False print(False)
输出结果
如果运行上面的程序,您将得到以下结果。
True
结论
如果在遵循本教程时遇到任何问题,请在评论部分中提及它们。
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短