我遇到了一个奇怪的问题。此代码返回 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 == ""
) 时,您将返回 1
或 2
。这会返回到调用函数——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/