-2

I'm coding a function in python, which is supposed to return the differents anagrams of a word. But when I test it, the function returns me none. Could you help me please ? Thank you very much ;)

My code :

import random

def factorial(number):
  result = 1

  for i in range(1, number + 1):
    result *= i
  
  return result


def find_anagrams(word):
  letters = []
  anagramms = []
  
  for letter in word:
    letters.append(letter)
  
  possibilities = factorial(len(letters))
  tries = 0
  
  while tries < possibilities:
    random.shuffle(letters)
    new_word = letters[0]
    
    for i in range(1, len(letters)):
      new_word += letters[i]
    
    if new_word not in anagramms:
      anagramms.append(new_word)  
      tries += 1


print(find_anagrams("hello"))


YogS
  • 1
  • 2
    add the return statement `return anagramms` to you function – Serge May 10 '21 at 10:28
  • 1
    also better use permutaions than random shuffle – Serge May 10 '21 at 10:30
  • Does this answer your question? [producing all the anagrams from a string python](https://stackoverflow.com/questions/11989502/producing-all-the-anagrams-from-a-string-python) – lorenzozane May 10 '21 at 10:30
  • Oh thank you I am so dumb ^^ x) – YogS May 10 '21 at 10:30
  • @Serge 's suggestion is absolutely critical but not enough. Your code gets stuck in an infinite loop. You're incrementing `tries` inside an `if` that may never be executed until the `while` condition becomes false. Having said that, your code doesn't even give the certainty that all possible anagrams will be generated at each execution. – lorenzozane May 10 '21 at 10:44
  • as I mentioned in the second comment, `itertool.permutations` solves the problem. – Serge May 10 '21 at 11:54

1 Answers1

0

Few challenges in your code/style

  1. Missing return statement in your find_anagrams. Your code is doing compute but your are not passing it down your print functions

  2. Using random.shuffle is not correct. Random sometimes does repeat. Is it correct?

  3. What happens to your code if the input has duplicate chars ? Lot of redundant work.

I would suggest you to look into Depth First Search (DFS) or Recursion or Backtracking algorithm here. With out one of these, your code won't be able to perform all required operations.

In case you have a dictionary of words, using a graph algo DFS along with Tries data structure would be more cost efficient.

sam
  • 1,819
  • 1
  • 18
  • 30