大家好,我是初學者,我想問一下這是一種不對(是字謎)問題中的字符進行排序的好方法我看到了一些教程,他們對字串進行了排序,但是我撰寫了一個演算法而不對字串進行排序,它在目標。
def is_anagram(str1, str2):
if len(str1) != len(str2):
return False
else:
for i in range(len(str2)):
if str1[i] not in str2 or str2[i] not in str1:
return False
return True
return False
print(is_anagram("hey", "hey"))
它比教程非常簡單,當我檢查它在大約 200 萬長度的字串上的運行時間為 1 秒時。
謝謝你需要你的考慮。
uj5u.com熱心網友回復:
嘗試這個:
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
例子:
>>> is_anagram("pat", "tap")
True
>>> is_anagram("hell", "heel")
False
>>>
如果您想完全自己撰寫它,您可以dict為每個字串創建一個,其中鍵是單個字符,值是該字符的出現次數。然后比較字典。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/514760.html
上一篇:如何按特定范圍計算串列中的每個專案?另外,為什么我的輸出中的最后一項沒有排序?
下一篇:給定一組優先級對/規則時如何排序
