[英]Even after entering the else of if -else the return statement is not working in Python?
def quickSort(nums,start,end):
if(start < end):
Pindex =partition(nums,start,end)
quickSort(nums,start,Pindex-1)
quickSort(nums,Pindex+1,end)
else:
print("Else",start,end,nums)
return nums;
The return statement is not executed even if the print ("Else",start,end,nums0 is executed即使执行了 print("Else",start,end,nums0 也不执行 return 语句
The problem is that you are ignoring the return values from your recursive quickSort
calls (which, by the way, is conventionally spelled quicksort
).问题是您忽略了递归
quickSort
调用的返回值(顺便说一下,它通常拼写为quicksort
)。
So even though your base case (the else
) returns a value, it will subsequently be discarded.因此,即使您的基本情况(
else
)返回一个值,它也会随后被丢弃。
You need to handle the return values of both recursive quicksort
calls:您需要处理两个递归
quicksort
调用的返回值:
quicksort
callquicksort
调用的变量Adjusting the code, and fixing the formatting, we get:调整代码并修复格式,我们得到:
def quicksort(nums, start, end):
if start < end:
pindex = partition(nums, start, end)
nums = quicksort(nums, start, pindex - 1)
return quicksort(nums, pindex + 1, end)
else:
return nums
Furthermore, it is conventional to handle the base case of a recursion first , because then we don't need to indent as much (since we also don't need the else
):此外,通常首先处理递归的基本情况,因为这样我们就不需要缩进太多(因为我们也不需要
else
):
def quicksort(nums, start, end):
if start >= end:
return nums
pindex = partition(nums, start, end)
nums = quicksort(nums, start, pindex - 1)
return quicksort(nums, pindex + 1, end)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.