[英]Value prints correctly in function, but when returned is None
我只是想复习python,所以我确定自己在这里犯了一个基本错误。 我的代码只是一个玩具应用程序,可以在圆形排序的数组中找到最大的项。
这是我的代码:
def listIsSorted(l):
if l[0] < l[-1]:
return 1
return 0
def findLargest(l):
listLength = len(l)
if(listLength == 1):
return l[0]
if(listLength == 2):
if(l[0] > l[1]):
print("OMG I Found it: " + str(l[0]))
return l[0]
return l[1]
halfway = int(listLength/2)
firsthalf = l[:int(halfway)]
secondhalf = l[int(halfway):]
if(listIsSorted(firsthalf) and listIsSorted(secondhalf)):
return max(l[halfway - 1], l[-1])
elif (listIsSorted(firsthalf)):
findLargest(secondhalf)
else:
findLargest(firsthalf)
l4 = [5,1,2,3]
print(findLargest(l4))
并输出以下内容:
OMG I Found it: 5
None
我的问题是:为什么只打印为5时为什么返回None
类型?
我猜它必须以这种方式修改,因为您忘记了返回递归调用的结果:
def findLargest(l):
listLength = len(l)
if listLength == 1:
return l[0]
if listLength == 2:
if l[0] > l[1]:
print "OMG I Found it: {0}".format(l[0])
return l[0]
return l[1]
halfway = int(listLength/2)
firsthalf = l[:int(halfway)]
secondhalf = l[int(halfway):]
if listIsSorted(firsthalf) and listIsSorted(secondhalf):
return max(l[halfway - 1], l[-1])
elif listIsSorted(firsthalf):
return findLargest(secondhalf)
else:
return findLargest(firsthalf)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.