0

这是我第二次就 MIT edX 课程的任务向你寻求帮助。

任务是:如果一个单词按顺序包含字母 e、r、i 和 c,则认为它是 erician。例如,我们会说以下单词是 erician:“meritocracy”、“generic”、“derrick”、“euphoric”、“heretic”和“electric”,因为它们每个都包含这四个字母的正确顺序。“大米”这个词不是erician,因为四个字母出现的顺序错误。

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

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

这是我的函数代码:

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_ian().line49: return True 完成了执行

然而该函数返回无。

将不胜感激任何帮助。

4

3 回答 3

2

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

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

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

您的代码可以简化为:

def x_ian(x, word):
    if not x or x == word:
        return True
    if len(x) > len(word):
        return False
    if x[0]==word[0]:
        return x_ian(x[1:], word[1:])
    return x_ian(x, word[1:])
于 2012-11-01T17:50:21.627 回答
0

您将得到 None 的回报,因为并非所有分支都返回一个值。这两个递归调用需要返回它们的结果。就像是:

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

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

于 2012-11-01T17:53:30.147 回答
0

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

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

利用这一点,我们将首先检查 x[0] 是否像这样从字符串中返回索引

try:
   word.index(x[0])
except:
   # do something ...

如果 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:])

您可以在此处查看运行代码。

于 2015-08-09T19:23:02.147 回答