寫一個 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/zh-hk/n/127092.html