一段 python 代码里的迭代看不懂,求解

2015-08-03 08:59:16 +08:00
 DannyVim
def is_reducible(word, word_dict):
    if word in memo:
        return memo[word]
    res=[]
    for child in children(word, word_dict):        
        t=is_reducible(child, word_dict) 
        #这里的迭代什么时候结束啊,传给t的到底是哪些值呢?
        if t:
        #这里是指t不是空集吗?
            res.append(child)
    memo[word]=res                                            
    return res

def children(word, word_dict):
    res=[]
    for i in range(len(word)):
        child=word[:i]+word[i+1:]
        if child in word_dict:
            res.append(child)
    return res

如果可以的话,能不能用一个单词举例子呢?

2996 次点击
所在节点    Python
9 条回复
monkeylyf
2015-08-03 09:15:02 +08:00
where is var 'memo' defined?
zerh925
2015-08-03 09:23:01 +08:00
child = word[:i] + word[i+1:]
这一段意思不是从word中去除一个字母吗?
那什么情况下去除了一个字母反而会变成一个单词?
加入word = congratulation, 无论i=多少,child都不是一个正确的单词吧?
根据你函数名称,是要找长单词中的最小有意义的短单词?
比如,uncomfortable中找comfort?
sinux
2015-08-03 09:37:49 +08:00
不是递归了一下嘛
tomwen
2015-08-03 09:56:52 +08:00
ie :
children('bread') => ['read', 'brad','bred']
-->children('read') => ['red',]
---->children('red') =>[] 迭代停止

-->children('brad')=> ['bad',]
...

-->children('bred')=> ['red']
....
DannyVim
2015-08-03 11:22:16 +08:00
@tomwen 传给res的值是当t为空集时的child吗?
DannyVim
2015-08-03 11:24:43 +08:00
@monkeylyf 这里不必管它了。
@zerh925 是要找出所有更短的单词。
tomwen
2015-08-03 11:32:36 +08:00
res只是一个局部变量,在每个函数中间都是先初始化为一个空列表,如果有符合条件的就放进去,如果没有结果就是空列表,最后遍历结束后返回res。
只是碰巧在两个函数中间都使用了同样的名字局部变量res而已,他们之间没有关系。
DannyVim
2015-08-03 13:45:53 +08:00
@tomwen 在‘is_reducible’这个函数里面,如果t为空集,则把此时的‘child’放进‘res’吗?例如是把‘red’放进去,而‘read’并不会被放进去吗?
tomwen
2015-08-03 14:10:52 +08:00
Just try it.
Insert "print word,res" after the 4th line, and run it.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/210342

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX