Created
May 24, 2012 01:02
-
-
Save paulogeyer/2778716 to your computer and use it in GitHub Desktop.
udacity cs212 unit 6 exercise #7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ----------------- | |
# User Instructions | |
# | |
# Write a function, extend_prefix, nested in find_words, | |
# that checks to see if the prefix is in WORDS and | |
# adds that to results if it is. | |
# | |
# If not, your function should check to see if the prefix | |
# is in PREFIXES, and if it is should recursively add letters | |
# until the prefix is no longer valid. | |
def prefixes(word): | |
"A list of the initial sequences of a word, not including the complete word." | |
return [word[:i] for i in range(len(word))] | |
def removed(letters, remove): | |
"Return a str of letters, but with each letter in remove removed once." | |
for L in remove: | |
letters = letters.replace(L, '', 1) | |
return letters | |
def readwordlist(filename): | |
file = open(filename) | |
text = file.read().upper() | |
wordset = set(word for word in text.splitlines()) | |
prefixset = set(p for word in wordset for p in prefixes(word)) | |
return wordset, prefixset | |
WORDS, PREFIXES = readwordlist('words4k.txt') | |
def find_words(letters): | |
results = [] | |
def extend_prefix(w, letters): | |
if w in WORDS: results.append(w) | |
if w not in PREFIXES: return | |
for L in letters: | |
extend_prefix(w+L, letters) | |
extend_prefix('', letters) | |
return set(results) | |
print find_words('ZYMURGY') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment