Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Define the path to the system dictionary file on Ubuntu
- dictionary_file_path = '/usr/share/dict/words'
- def get_four_letter_words(file_path):
- four_letter_words = []
- with open(file_path, 'r') as file:
- for line in file:
- word = line.strip()
- word = word.lower()
- if len(word) == 4:
- four_letter_words.append(word)
- return four_letter_words
- four_letter_words_array = get_four_letter_words(dictionary_file_path)
- def is_adjacent(word1, word2):
- if ((word1[0] == word2[0]) + (word1[1] == word2[1]) + (word1[2] == word2[2]) + (word1[3] == word2[3])) == 3: return True
- return sorted(word1) == sorted(word2)
- def all_adjacent(word):
- return filter(lambda w: is_adjacent(word, w), four_letter_words_array)
- def difference(word1, word2):
- diff = list(word2)
- for let in word1:
- if let in diff:
- diff.remove(let)
- return len(diff) + (word1[0] != word2[0]) + (word1[1] != word2[1]) + (word1[2] != word2[2]) + (word1[3] != word2[3])
- def path_to(fr, to, path=[], d=None):
- path = path + [fr]
- d = d if d is not None else difference(fr, to)
- if d == 0:
- return path
- for word in all_adjacent(fr):
- if word in path: continue
- d2 = difference(word, to)
- if d2 < d:
- npath = path_to(word, to, path, d2)
- if npath: return npath
- word = "word"
- while True:
- inp = input(f"word is {word} > ").lower()
- if len(inp) == 4:
- word = inp
- elif inp.startswith("-t"):
- try:
- to = inp.split()[1]
- assert len(to) == 4
- except:
- print("incorrect command for -t")
- continue
- path = path_to(word, to)
- if not path: print("No path found")
- else:
- print(f"words leading from {word} to {to}")
- for w in path:
- print(f" {w}")
- elif inp == "-l":
- print(f"words adjancent to {word}")
- for adjacent_word in all_adjacent(word):
- print(f" {adjacent_word}")
- elif inp == "-q":
- print("Goodbye.")
- break
- else:
- print("""Enter a four letter word to set the current word.
- commands:
- -t {word}
- [to {word}] find a path from word to word.
- -l
- [list] list all adjacent words.
- -q
- [quit]""")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement