Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

An anagram solver program in Python can be created using the following steps:

  1. Take a user input word or phrase.
  2. Convert the input to lowercase and remove any non-alphabetic characters using regular expressions.
  3. Get a list of all possible permutations of the letters in the input word using the itertools module.
  4. Load a dictionary file containing a list of words.
  5. Check each permutation of letters against the words in the dictionary file.
  6. If a match is found, add it to a list of anagrams.
  7. Print the list of anagrams.

Here's an example code:

import itertools
import re

# Load dictionary file
with open('dictionary.txt', 'r') as file:
    dictionary = [word.strip() for word in file.readlines()]

# Get input word/phrase from user
input_str = input('Enter a word or phrase: ')

# Remove non-alphabetic characters and convert to lowercase
input_str = re.sub(r'[^a-zA-Z]', '', input_str).lower()

# Get all permutations of letters
perms = [''.join(perm) for perm in itertools.permutations(input_str)]

# Check each permutation against dictionary
anagrams = []
for word in perms:
    if word in dictionary:
        anagrams.append(word)

# Print list of anagrams
print(anagrams)

Note: The dictionary file used in this example must contain one word per line.