Codewars第六天–Where my anagrams at?
题目描述:
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
Write 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']) => []
该题目是需要我们找到同给定字符串有着相同数目的字母的字符串,并返回这些字符串的列表。如果没有则返回空列表。
代码如下,使用了比较笨的方法,但也通过了所以的用例,在这里需要分别对比字符串之间的字符和字符个数情况。
使用set
可以对字符串去重,并返回一个去重过后的对象。使用count
可以对字符串中相应的字符进行统计个数。
def anagrams(word, words):
w = set(word)
a = [word.count(j) for j in w]
result = []
for i in words:
ws = set(i)
b=[i.count(j) for j in ws]
if ws == w:
if a == b:
result.append(i)
return result
最佳做法一句话就可以搞定:
def anagrams(word, words): return [item for item in words if sorted(item)==sorted(word)]