1

Fairly new to Python but I'm trying to make a Scrabble anagram solver which will loop through a large text file and check for anagrams with a user given 7 letter rack. I'm working on the is_anagram function and using sorted() to make a list of the letters in the word in alphabetical order and then using a if statement to see if the sorted word from the dictionary is equal to the sorted rack of letters provided. Because the letters that are being searched come from a long list there is a "\n" in the list created from the words which makes it so they are not equal. I'm trying to set up the iteration so that it removes '\n' from the list before comparing it ,but for some reason it is returning the list as None instead of the list minus '\n'. Not sure why. Anyone can help? Code is below:

def is_anagram(word):
    scrabble_dict = open('sowpods.txt')
    for x in scrabble_dict:
        x = sorted(x)
        x = x.remove('\n')
        word = sorted(word)
        if word == x:
            print(word)
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Check this question: http://stackoverflow.com/questions/26766587/removing-item-from-list-causes-the-list-to-become-nonetype Basically remove does not work like that. You don't need `x = x.remove('\n')` just `x.remove('\n')` is enough. – Fma Aug 12 '16 at 14:29
  • Answers the question! Thanks! –  Aug 12 '16 at 14:34
  • won't printing word after sorting it just print gibberish? Also isn't `word` the letters that the player has on his rack, and instead `x` is the actual word in the dictionary? If my understanding is correct, you want to save a copy of `x` before sorting, and if there is a match, print the saved copy so you actually get a word? also using `if x in word` might be a better call, since it will allow you to check for dictionary entries that are smalled than `word` – dheiberg Aug 12 '16 at 14:39
  • Yeah, I noticed that after I figured out the issue with remove. I just set y = sorted(x) and used y as the variable and then had the function return x. –  Aug 12 '16 at 15:02

1 Answers1

1

You don't need to assign x again after removing the newline.

def is_anagram(word):
    scrabble_dict = open('sowpods.txt')
    for x in scrabble_dict:
        x = sorted(x)
        x.remove('\n')
        word = sorted(word)
        if word == x:
            print(word)
dheiberg
  • 1,914
  • 14
  • 18
jackiezhu
  • 422
  • 3
  • 8