Python sorted()检查两个字符串是否为字谜

2021年4月8日17:46:22 发表评论 929 次浏览

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

例子:

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


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

Python提供了内置功能sorted()不会修改原始字符串, 但返回已排序的字符串。

以下是上述方法的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)

输出如下:

The strings are anagrams.

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: