因此,我试图从think中解决这个问题:
第12章练习6:
什么是最长的英语单词,它仍然是一个有效的英语单词,因为你删除它的字母一次一个? 现在,字母可以从两端或中间移除,但不能重新排列任何字母。每次你丢下一封信,你就会得到另一个英文单词。如果你这样做,你最终会得到一个字母,这也将是一个英语单词-一个在字典中找到的。我想知道最长的单词是什么,它有多少个字母? 我要给大家举一个小小的例子:雪碧。好的?你从雪碧开始,你取下一封信,一封从字的内部取走,把r取走,剩下的是“恨”这个词,然后我们把e从结尾取下来,剩下的是唾沫,我们把它取下来,剩下的是坑,它,还有我。 编写一个程序,找出所有可以用这种方式减少的单词,然后找出最长的单词。
我开始编写一些函数,但我仍然停留在check_dict函数上:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def word_list(textfile='words.txt'):
res = {}
for word in open(textfile):
word = word.strip()
res[word] = word
return res
def children(s, wl):
i = 0
children = []
while i < len(s):
temp = s[:i] + s[i+1:]
if temp in wl:
children.append(temp)
i += 1
return children
def check_dict(s, wl, res = [], called = 0):
if len(s) == 1 and s in wl:
res.append(s)
return res
else:
for child in children(s, wl):
#print(res,'call number ', str(called), 'with s = ', s, 'whose children are: ', children(s, wl))
res.append(child)
check_dict(child, wl, res, called+1)
wl = word_list()
print(check_dict('at', wl))我遇到的问题是,它不返回res的内容,而是返回res的内容,除非我使用基大小写运行函数,即s= 'a‘或s= 'i’。我知道这个函数贯穿于所有可能的路径,因此它应该返回几个不同的res,但是我不太明白如何才能让这个函数只打印一个从调用函数的参数一直到满足基本大小写条件的长s。
我知道这本书上有一个解决方案,但我想知道我做错了什么,如何修正我的版本。
发布于 2014-12-24 20:20:12
1您需要更改word_list函数,您的word_list函数给出的dict只有一个键和值相同的项,即文件内容。更改函数,从input.txt文件中获取单词列表
2在check_dict函数中,将返回函数写在if-else循环之外,因为子函数返回空列表。
def word_list(textfile='input.txt'):
return open(textfile).read().strip().split(" ")
def children(s, wl):
i = 0
children = []
s_len = len(s)
while i < len(s):
temp = s[:i] + s[i+1:]
if temp in wl:
children.append(temp)
i += 1
return children
def check_dict(s, wl, res = [], called = 0):
if len(s) == 1 and s in wl:
res.append(s)
else:
for child in children(s, wl):
#print(res,'call number ', str(called), 'with s = ', s, 'whose children are: ', children(s, wl))
res.append(child)
check_dict(child, wl, res, called+1)
return res
wl = word_list()
a = check_dict('sprite', wl)https://stackoverflow.com/questions/27641152
复制相似问题