【每日一题20220905】我的字谜在哪里?

:magic_wand: 什么是字谜?如果两个单词都包含相同的字母,则它们是彼此的字谜。例如:

'abba' & 'baab' == true

'abba' & 'bbaa' == true

'abba' & 'abbba' == false

'abba' & 'abca' == false

编写一个函数,从列表中查找单词的所有字谜。您将获得两个输入一个单词和一个带有单词的数组。您应该返回一个包含所有字谜的数组,如果没有字谜,则应返回一个空数组。例如:

anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']

anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']

anagrams('laser', ['lazing', 'lazy',  'lacer']) => []

题目难度:一般
题目来源: 我的字谜在哪里?|码战 (codewars.com)

def anagrams(word: str, words: list) -> list :
    #your code here

assert anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) == ['aabb', 'bbaa']
assert anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) == ['carer', 'racer']
assert anagrams('laser', ['lazing', 'lazy',  'lacer']) == []
1 个赞
def anagrams(word,words):
    return [i for i in words if sorted(i)==sorted(word)]

def anagrams(word: str, words: list) -> list:
    lresult = words.copy()
    for i in words:
        if len(i) != len(word):
            lresult.remove(i)
        else:
            if sorted(i) != sorted(word):
                lresult.remove(i)
    return lresult
def anagrams(word: str, words: list) -> list:
    """
    从列表中查找单词的所有字谜。
    :param word: 单词
    :param words: 单词列表
    :return: 字谜列表
    """
    def gen_words(w: str, ws: list):
        for item in ws:
            if sorted(item) == sorted(w):
                yield item

    return list(gen_words(word, words))


assert anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) == ['aabb', 'bbaa']
assert anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) == ['carer', 'racer']
assert anagrams('laser', ['lazing', 'lazy', 'lacer']) == []
def anagrams(word: str, words: list) -> list :

	return [words[i] for i in range(len(words)) if sorted(words[i])==sorted(word)]



assert anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) == ['aabb', 'bbaa']
assert anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) == ['carer', 'racer']
assert anagrams('laser', ['lazing', 'lazy',  'lacer']) == []
def anagrams(word: str, words: list) -> list :
    new_words=[words[i] for i in range(len(words)) if len(words[i])==len(word)]
    word_set=sorted({(word[i],word.count(word[i])) for i in range(len(word))},key=lambda x:x[0])
    return [new_words[i] for i in range(len(new_words)) if sorted({(new_words[i][j],new_words[i].count(new_words[i][j])) for j in range(len(new_words[i]))},key=lambda x:x[0])==word_set]

assert anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) == ['aabb', 'bbaa']
assert anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) == ['carer', 'racer']
assert anagrams('laser', ['lazing', 'lazy',  'lacer']) == []