What is an anagram? Well, two words are anagrams of each other if they both contain the >same letters. For example:
'abba' & 'baab' == true
'abba' & 'bbaa' == true
'abba' & 'abbba' == false
'abba' & 'abca' == falseWrite a function that will find all the anagrams of a word from a list. You will be >given two inputs a word and an array with words. You should return an array of all the >anagrams or an empty array if there are none. For example:
anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']
anagrams('laser', ['lazing', 'lazy', 'lacer']) => []
題目理解:設計一函式含有兩參數,字串word&列表words。若words中有字串與word互為字謎關係(anagrams),則將其返還。
依題目,若兩數所有組成字元的種類連同數量皆相同,則互為字謎。故可利用dict型別來將string中的字元種類和數量做保存,若有字串依此方式轉換成dict後與題目word轉換後相同,即可判斷彼此互為字謎關係。
def string_to_dict(str):
"""將字串轉換為dict形式儲存"""
dic = {}
#利用set()將str內的字元種類作為key,並用count()計算字元出現在str內的數量並作為value儲存
for char in set(str):
dic[char] = str.count(char)
return dic
def anagrams(word, words):
reslut = []
#將word轉換為dict儲存,稍後作為對照組使用
key_word_dict = string_to_dict(word)
#逐一比較words中的字串轉換為dict形式後是否與key_word_dict相同,若相同則將該字串加入reslut
for i in range(len(words)):
if string_to_dict(words[i]) == key_word_dict:
reslut.append(words[i])
return reslut