Home > OS >  Checking if a scrambled word is part of a dictionary
Checking if a scrambled word is part of a dictionary

Time:05-27

I have a task where I have to make a python code/program for the following:

Inputs:

  • Dictionary words (words are to be separated by a space)
  • Input word (a single scrambled word)

All words, including both the dictionary words and the scrambled word, consist only of lowercase English letters and will be at least one and at most six characters long. The dictionary is not necessarily in sorted order, but each word in the dictionary is unique.

The program should print "True" if one or more of the dictionary words can be formed (matched exactly) by rearranging the letters of the input word. Otherwise, the program should output "False".

Here are some examples:


Case 1:

If the input is:

work seven study air
rokw

Output is:

True

Case 2:

Input is:

one woman post course tree
omnw

Output is:

False

Case 3:

Input is:

one woman post course tree
tspos

Output is:

False

Case 4:

Input is:

one woman post course tree snap
namow

Output is:

False

I have here a program where the "True" is not being printed. I had a version where it would correctly detect up to 4 words, but if I write 5 dictionary words, it's wrong again. What could I be missing?

#Taking two inputs from user
dictionaryWords = input("Input:\n")
word = input()
# convert the string into a list of words
words = (dictionaryWords.split())
# declare a variable
flag = True
# access each word of the list
for i in words:
  # if particular word's length is equal to the given word's length
  if len(i) == len(word):
    # convert the word into characters of list
    word1 = list(i)
    word2 = list(word)
    # condition to find result
    for j in word:
      if j not in word1:
        flag = False
        break
# Display the output
print("Output:\n",flag)

CodePudding user response:

This approach seems overly complex. You can sort the letters of each word to find matches that are order-agnostic:

potential_matches = {''.join(sorted(word)) for word in dictionary_words.split()}
print(''.join(sorted(word)) in potential_matches)

CodePudding user response:

There are a couple of problems:

  • Your current approach to checking if the two words are anagrams is flawed, because, for example, blob contains l, o and b, but is not an anagram of lobl. It's possible to make it work, but an easier way is just to check if sorted(word1) == sorted(word2).
  • You have your boolean flag the wrong way round. It should start off as False and then become True when you find a word that matches. Otherwise any bad word (of the right length in your case) overrules all of the good ones.
  • Related