我有以下 Python 代码:
def find_words(letters):
results = set()
def extend_prefix(w, letters):
if w in WORDS: results.add(w)
if w not in PREFIXES: return
for L in letters:
result = extend_prefix(w + L, letters.replace(L, "", 1))
results = results | result
extend_prefix('', letters)
return results
print find_words("ABCDEFGH")
当我运行它时,我收到以下错误:
Traceback (most recent call last):
File "ExtendPrefix.py", line 44, in <module>
print find_words("ABCDEFGH")
File "ExtendPrefix.py", line 41, in find_words
extend_prefix('', letters)
File "ExtendPrefix.py", line 38, in extend_prefix
result = extend_prefix(w + L, letters.replace(L, "", 1))
File "ExtendPrefix.py", line 38, in extend_prefix
result = extend_prefix(w + L, letters.replace(L, "", 1))
File "ExtendPrefix.py", line 35, in extend_prefix
if w in WORDS: results.add(w)
UnboundLocalError: local variable 'results' referenced before assignment
它显然无法在对extend_prefix 的递归调用中找到结果。为什么会这样,我该如何解决?