又是来自Python的任务…edX

2024-04-20 07:20:45 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第二次向你寻求有关麻省理工学院edX课程任务的帮助。在

任务是: 一个单词如果按顺序包含字母e,r,i,c,则被认为是erician。例如,我们会说下面的单词是erician:“精英”,“通用”,“derrick”,“euphoric”,“exteric”和“electric”,因为它们都按照正确的顺序包含了这四个字母。“rice”这个词不是erician,因为这四个字母的顺序不对。在

在这个问题中,我们希望您编写一个更通用的函数x_ian(x,word),如果x的所有字母都以x中出现的顺序包含在word中,则返回True

这个函数必须是递归的!您不能(暂时或暂时)使用循环来解决此问题。

下面是我的函数代码:

if x=="":
        return True
if len(x)>len(word):
        return False
if x==word:
    return True
elif (x[0]==word[0]):
    x_ian(x[1:],word[1:])
else:
    x_ian(x,word[1:])

我现在不知道为什么我的函数返回None,而不是True或False。我在IDLE中使用了调试器,它使用 'main'.x\u ian().line49:返回True

但是函数没有返回。在

谢谢你的帮助。在


Tags: 函数falsetruelenreturnif顺序字母
3条回答

您需要返回递归调用的输出:

elif (x[0]==word[0]):
    return x_ian(x[1:],word[1:])
else:
    return x_ian(x,word[1:])

否则python只会到达函数的末尾,这意味着它将返回None;函数的默认返回值。在

可以简化代码:

^{pr2}$

在这里,.index()函数非常方便。字符串上的index()函数将始终返回作为参数传入的字母第一次出现的索引。所以

print 'abcdceg'.index('c') 
# will return 2 - the first occurrence of 'c' in the string

利用这一点,我们将首先检查x[0]是否从字符串返回一个索引,如下所示

^{pr2}$

如果x的第一个字母根本不存在于单词中,它将进入异常。但是,如果它确实返回了一个索引,我们会希望从第一次出现到单词结尾处修剪这个字符串,然后在x中查找连续的字母,就像这样,作为一个递归调用:

x_ian(x[1:], word[word.index(x[0]) + 1:])

现在,如果字符串没有返回索引,这意味着,可能有两种可能,要么x用完了字母,要么x中有一个字母在单词中不存在。所以,现在我们有一个例外情况:

try:
  word.index(x[0])
except:
  if len(x) == 0:
    return True
  else:
    return False

把它们放在一起

def x_ian(x, word):   
    # the .index will always return the 1st occurance's index
    try:
        word.index(x[0])
    except:
        if len(x) == 0:
            # at this point, all the letters in x have been checked
            #  in successive order, which means, it exists.
            return True
        else:
            # at this point, we encountered a letter in x that doesn't
            #  exist in word.
            return False

    return x_ian(x[1:], word[word.index(x[0]) + 1:])

您可以查看正在运行的代码here。在

您得到的返回值为None,因为不是所有分支都返回值。这两个递归调用需要返回结果。比如:

return x_ian(x[1:],word[1:])

如果函数从不调用return,那么python隐式返回None。在

相关问题 更多 >