[英]How does the return work inside a recursive function in Python?
I am having issues when returning the values from a recursive function.从递归 function 返回值时遇到问题。 For example, in a very simple function called 'RBinSearch', I am trying to find the index of the key in an array.例如,在一个名为“RBinSearch”的非常简单的 function 中,我试图在数组中查找键的索引。 Unfortunately, I just cannot able to return the value (answer should be 4) based on my understanding.不幸的是,根据我的理解,我无法返回值(答案应该是 4)。
For comparison, I have used a normal function with a loop to test the return (in a function called 'BinarySearch' here), which is working as expected.为了比较,我使用了一个普通的 function 和一个循环来测试返回(在 function 中称为“BinarySearch”),它按预期工作。 Can anyone please explain how the return behave inside a recursive function and where my understanding is incorrect?谁能解释一下递归 function 中的返回行为以及我的理解不正确的地方? Thanks!谢谢!
import math
import sys
def BinarySearch(array, key):
low=0
high=len(array)-1
while(low<=high):
mid=math.floor((low+high)/2)
if(key==array[mid]):
return mid
elif(key<array[mid]):
high=mid-1
elif(key>array[mid]):
low=mid+1
return -1
def RBinSearch(array,low,high,key):
if(low<=high):
mid=math.floor((low+high)/2)
print("Value of mid: ",mid)
if(key==array[mid]):
print("Found the value: ",mid)
return mid
sys.exit()
elif(key<array[mid]):
RBinSearch(array, low, mid-1, key)
else:
RBinSearch(array, mid+1, high, key)
return -1
arr=[4,8,10,15,18,21,24,27,29,33,34,37,39,41,43]
print("Index from while Bin search: ",BinarySearch(arr, 18))
print("The index found using the Binary search is: ",RBinSearch(arr, 0,len(arr)-1,18))
Output Output
You need to return RBinSearch
result in your RBinSearch
function:您需要在RBinSearch
function 中返回RBinSearch
结果:
def RBinSearch(array, low, high, key):
if low <= high:
mid = math.floor((low + high) / 2)
print("Value of mid: ", mid)
if key == array[mid]:
print("Found the value: ", mid)
return mid
elif key < array[mid]:
return RBinSearch(array, low, mid - 1, key)
else:
return RBinSearch(array, mid + 1, high, key)
return -1
Also you shouldn't use sys.exit()
.你也不应该使用sys.exit()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.