简体   繁体   English

为什么此函数不返回任何值而不是列表?

[英]Why does this function return none instead of the list?

Why does the function return none? 为什么函数不返回任何内容?

I thought list were passed by reference. 我认为清单是通过参考传递的。 I added return to the recursive call, it worked. 我将return添加到递归调用中,它起作用了。 But I'm just wondering why the return did made a difference. 但是我只是想知道为什么回报确实有所作为。

Note: I'm trying to learn recursion 注意:我正在尝试学习递归

def find_min_max(arr, i, nums):
  if i == len(arr):
    return nums

  if arr[i] < nums[0]:
    nums[0] = arr[i]
  if arr[i] > nums[1]:
    nums[1] = arr[i]

  find_min_max(arr, i+1, nums)

You miss a return statement in the last line, if you don't return anything, python by default returns None 您错过最后一行的return语句,如果您不返回任何内容,则python默认返回None

def find_min_max(arr, i, nums):
  if i == len(arr):
    return nums

  if arr[i] < nums[0]:
    nums[0] = arr[i]
  if arr[i] > nums[1]:
    nums[1] = arr[i]

  return find_min_max(arr, i+1, nums)

I added return to the recursive call, it worked. 我将return添加到递归调用中,它起作用了。 But I'm just wondering why the return did made a difference. 但是我只是想知道为什么回报确实有所作为。

It is the same as if you had called any other function in that spot ; 就像您在该位置调用过任何其他函数一样 the value only gets returned if you specify to return it. 仅当您指定返回值时才返回该值。 There is nothing special about calling a function recursively vs. any other calling of functions; 与其他任何函数调用相比,递归调用函数没有什么特别的。 there is only something special about writing correct logic that uses the technique :) 关于使用该技术编写正确的逻辑只有一些特别的事情:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM