📌  相关文章
📜  用于检查两个字符串是否为 Anagram 的Python程序

📅  最后修改于: 2022-05-13 01:54:45.423000             🧑  作者: Mango

用于检查两个字符串是否为 Anagram 的Python程序

问题:

给定两个字符串s1 和 s2,检查这两个字符串是否是彼此的字谜。
例子:

Input : s1 = "listen"
        s2 = "silent"
Output : The strings are anagrams.


Input : s1 = "dad"
        s2 = "bad"
Output : The strings aren't anagrams.

解决方案:

方法 #1:使用 sorted()函数

Python提供了一个内置函数sorted() ,它不会修改原始字符串,而是返回排序后的字符串。
以下是上述方法的Python实现:

Python
# function to check if two strings are
# anagram or not
def check(s1, s2):
     
    # the sorted strings are checked
    if(sorted(s1)== sorted(s2)):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")        
         
# driver code 
s1 ="listen"
s2 ="silent"
check(s1, s2)


Python3
# Python3 program for the above approach
from collections import Counter
 
# function to check if two strings are
# anagram or not
def check(s1, s2):
   
    # implementing counter function
    if(Counter(s1) == Counter(s2)):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")
 
 
# driver code
s1 = "listen"
s2 = "silent"
check(s1, s2)


输出
The strings are anagrams.

方法 #2:使用 Counter()函数

  • 计算第一个字符串和 2 的所有频率并使用 counter()
  • 如果它们相等,则打印字谜

Python3

# Python3 program for the above approach
from collections import Counter
 
# function to check if two strings are
# anagram or not
def check(s1, s2):
   
    # implementing counter function
    if(Counter(s1) == Counter(s2)):
        print("The strings are anagrams.")
    else:
        print("The strings aren't anagrams.")
 
 
# driver code
s1 = "listen"
s2 = "silent"
check(s1, s2)
输出
The strings are anagrams.