python - 想想 Python : Chapter 12 Exercise 6

标签 python algorithm recursion data-structures iteration

所以我试图从 think python 解决这个练习:

第 12 章的练习 6:

What is the longest English word, that remains a valid English word, as you remove its letters one at a time?

Now, letters can be removed from either end, or the middle, but you can’t rearrange any of the letters. Every time you drop a letter, you wind up with another English word. If you do that, you’re eventually going to wind up with one letter and that too is going to be an English word—one that’s found in the dictionary. I want to know what’s the longest word and how many letters does it have?

I’m going to give you a little modest example: Sprite. Ok? You start off with sprite, you take a letter off, one from the interior of the word, take the r away, and we’re left with the word spite, then we take the e off the end, we’re left with spit, we take the s off, we’re left with pit, it, and I.

Write a program to find all words that can be reduced in this way, and then find the longest one.

我开始编写一些函数,但我卡在了 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))

我遇到的问题是它返回 None 而不是返回 res 的内容,除非我使用 s = 'a' 或 s = 'i' 的基本情况运行该函数。我知道这个函数遍历每条可能的路径,因此它应该返回几个不同的 res,但我不太明白我怎么能让这个函数只打印一个 res,它从函数的参数一直到被称为满足基本情况条件的 1 个字母长的 s。

我知道这本书上有一个解决方案,但我想知道我做错了什么以及如何修复我的版本。

最佳答案

1 您需要更改 word_list 函数,您的 word_list 函数给出的字典只有一个键和值相同的项目,即文件内容。更改函数以从 input.txt 文件中获取单词列表

2 在 check_dict 函数中,将 return 函数写在 if-else 循环之外,因为 children(s, wl) 函数返回空列表。

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)

关于python - 想想 Python : Chapter 12 Exercise 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27641152/

相关文章:

python - Moviepy 滑入和滑出过渡

python - 组合正则表达式模式以匹配字符串的开头和结尾并删除分隔符

Python - 混合两个音频 block

python - VSCode - 在调试时显示图像

string - 为字符串生成校验和

algorithm - 每个字符连续出现之后

algorithm - 删除二叉树中所有不在任何路径上且 sum>= k 的节点

java - ConcurrentModificationException 在 Java 中递归使用 Maps

java - 从另一个类调用方法并检索其结果 (Java)

python - 保存递归函数的多个值