python - return 语句返回 None 而不是 value

标签 python procedures

我遇到了一个奇怪的问题。此代码返回 None 而不是 True,即使它进入正确的分支并评估为 True:

edges = { (1, 'a') : [2, 3],
          (2, 'a') : [2],
          (3, 'b') : [4, 3],
          (4, 'c') : [5] }
accepting = [2, 5] 
loc = []
def nfsmsim(string, current, edges, accepting): 

    if string != "":
        if ((current, string[0]) in edges.keys()):
            global loc 
            loc = edges[(current, string[0])]
            print "edge found:",loc

    if (string == ""):
        print "string is over",current,accepting
        print type(current), type(accepting)
        if current in accepting : 
            print "1"
            return True
        else: 
            print "2"
            return 2
    # fill in your code here 
    elif (current, string[0]) in edges.keys():
        global loc
        string = string[1:]
        nfsmsim(string, loc[0], edges, accepting)
    elif len(loc)>1:
        global loc
        nfsmsim(string, loc[1], edges, accepting)


# This problem includes some test cases to help you tell if you are on
# the right track. You may want to make your own additional tests as well.
print nfsmsim("abc", 1, edges, accepting)

这个的输出是:

 string is over 5 [2, 5]
<type 'int'> <type 'list'>
1
None (<< instead of True)

最佳答案

这是一个递归函数。当您到达终端案例 (string == "") 时,您将返回 12。这会返回到调用函数——nfsmsim 的先前调用。但是 nfsmsim 的调用没有返回任何内容!您需要从 nfsmsim 的终端调用中获取值,并通过再次返回来传递它。

换句话说,您的 if 语句的这两个分支中的每一个都需要一个 return 语句:

elif (current, string[0]) in edges.keys():
    global loc
    string = string[1:]
    nfsmsim(string, loc[0], edges, accepting)
elif len(loc)>1:
    global loc
    nfsmsim(string, loc[1], edges, accepting)

关于python - return 语句返回 None 而不是 value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10274792/

相关文章:

python - 该组件的 Prop 无效

python pandas 计算连续交易中的重复项目

javascript - 新数据行上的 SQL 更新列

mysql - 如何对 MySQL 过程进行故障排除 - 为什么循环达到最大运行次数?

Python:查找文本中的单词列表并返回其索引

当没有参数给出错误时,Python类自变量作为默认值

mysql - MySQL "DELIMITER"关键字无效

mysql - 如何编写 MySQL 触发器以将行插入另一个表?

javascript - 添加 Bokeh curdoc 的自定义脚本