正如其他人指出你是在爲你的列表尋找字謎的所有組話。這裏你有一個可能的解決方案。該算法查找候選對象並選擇一個(第一個元素)作爲規範詞,並將其餘的詞作爲可能詞刪除,因爲anagrams是可傳遞的,並且一旦您發現某個詞屬於anagram組,則不需要重新計算它。
input = ["umbellar","goa","umbrella","ago","aery","alem","ayre","gnu",
"eyra","egma","game","leam","amel","year","meal","yare","gun",
"alme","ung","male","lame","mela","mage" ]
res = dict()
for word in input:
res[word]=[word]
for word in input:
#the len test is just to avoid sorting and comparing words of different len
candidates = filter(lambda x: len(x) == len(word) and\
sorted(x) == sorted(word),res.keys())
if len(candidates):
canonical = candidates[0]
for c in candidates[1:]:
#we delete all candidates expect the canonical/
del res[c]
#we add the others to the canonical member
res[canonical].append(c)
print res.values()
這algth輸出...
[['year', 'ayre', 'aery', 'yare', 'eyra'], ['umbellar', 'umbrella'],
['lame', 'leam', 'mela', 'amel', 'alme', 'alem', 'male', 'meal'],
['goa', 'ago'], ['game', 'mage', 'egma'], ['gnu', 'gun', 'ung']]
它這個功課?如果是這樣,那麼標記它。 –
假設一個相同的單詞必須具有相同的長度,然後對列表中的每個字符串進行排序並檢查匹配。 –