0

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.

Hi can some kind soul explain to me how this 2 function is different? One only returns the first value the for loops found.... why is that so?

def anagrams(word, words):
    for item in words:
        if sorted(item) == sorted(word):
            return [item]

def anagram(word, words):
    return [item for item in words if sorted(item) == sorted(word)]

print(anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']))
print(anagram('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']))

['carer']

['carer', 'racer']

Junhao
  • 3
  • 1
  • 3
    `return` causes the function to exit. You'd use `yield` to do what you're trying to do; although that's a more advanced feature of the language. – Carcigenicate Jul 11 '21 at 14:26
  • If you want to get the same results (multiple matching words) and keep the similar `for-loop` then you need to add a `result (list)` to keep all matching anagrams. – Daniel Hao Jul 11 '21 at 14:42

1 Answers1

0
def anagram(word, words):
    return [item for item in words if sorted(item) == sorted(word)]
def anagram(word, words):
    final_list = []
    for item in words:
        if sorted(item) == sorted(word):
            final_list.append(item)
    return final_list

Both will do the same work

your anagrams function return after finding one match which causes function to exit

A return statement ends the execution of a function, and returns control to the calling function

You can also use generator function

def anagram(word, words):
    for item in words:
        if sorted(item) == sorted(word):
            yield item
   
print(anagram('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']))

"""This returns a generator object, so you need to convert it to list"""

print(list(anagram('racer', ['crazer', 'carer', 'racar', 'caers', 'racer'])))

k4anubhav
  • 110
  • 1
  • 9