写一个 Python 程序来检查两个字符串是否是异序词。例如,如果一个字符串通过重新排列其他字符串字符而形成,则它是一个异序词字符串。例如,三角形和积分都将通过重新排列字符而形成。
在本 Python 示例中,sorted 方法按字母顺序对两个字符串进行排序,if 条件检查两个排序后的字符串是否相等。如果为真,则两个字符串是异序词。
str1 = input("Enter the First String = ")
str2 = input("Enter the Second String = ")
if(sorted(str1) == sorted(str2)):
print("Two Strings are Anagrams.")
else:
print("Two Strings are not Anagrams.")
Enter the First String = listen
Enter the Second String = silent
Two Strings are Anagrams.
Python 程序检查两个字符串是否是异序词或者没有使用集合库中的计数器。
from collections import Counter
str1 = input("Enter the First String = ")
str2 = input("Enter the Second String = ")
if(Counter(str1) == Counter(str2)):
print("Two Strings are Anagrams.")
else:
print("Two Strings are not Anagrams.")
Enter the First String = race
Enter the Second String = care
Two Strings are Anagrams.
Enter the First String = dare
Enter the Second String = care
Two Strings are not Anagrams.
原创文章,作者:W3E3V,如若转载,请注明出处:https://www.506064.com/n/127092.html