【问题标题】:How does the return work inside a recursive function in Python?在 Python 的递归函数中,return 是如何工作的?
【发布时间】:2022-01-15 02:21:38
【问题描述】:

从递归函数返回值时遇到问题。例如,在一个名为“RBinSearch”的非常简单的函数中,我试图在数组中查找键的索引。不幸的是,根据我的理解,我无法返回值(答案应该是 4)。

为了比较,我使用了一个带有循环的普通函数来测试返回(在此处称为“BinarySearch”的函数中),它按预期工作。谁能解释一下递归函数中返回的行为以及我的理解不正确的地方?谢谢!

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))
 

输出

【问题讨论】:

  • 您使用递归来找到正确的位置 - 然后忽略结果,然后return -1。你想要return RBinSearch(...)。此外,风格方面,在 Python 中,您应该将 snake_case 用于函数(和变量); TitleCase 通常用于类名。
  • @Amadan 当然可以,但是在递归函数中获取值后如何返回结果?在此示例中,我想在 RBinSearch 中返回变量“mid”的值,但该函数一直返回 -1。为什么会发生这种情况?
  • 正如我所描述的,正如 Ratery 回答的那样,但使​​用 return 将下级结果传回。您的终端调用返回mid,但它只返回上一级;中间水平并没有进一步向上传播该值。他们改为返回-1。 tl; dr:该函数一直返回 -1,因为您告诉它。 :)
  • 想象一个类比,一个消防桶链。你告诉人们“如果你在河边,把桶装满然后给下一个人。如果不是,小心地抓住给你的桶,然后大喊你收到了。”你认为水能走多远?直到第二个人,因为你没有告诉人们远离河流去传递水桶。

标签: python recursion


【解决方案1】:

您需要在您的RBinSearch 函数中返回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

你也不应该使用sys.exit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多