[英]Python global variable not working in recursive function
I wrote a quicksort program with Python and my goal here is to calculate total comparisons used. 我用Python编写了一个quicksort程序,我的目标是计算使用的总比较。 I declared a global variable named
thesum
. 我声明了一个名为
thesum
的全局变量。 When I use thesum
in the partition function, I can calculate the thesum
correctly. 在分区函数中使用
thesum
时,我可以正确计算thesum
。 However, when I tried to calculate the sum in the recursive function it gave wrong answers. 但是,当我尝试在递归函数中计算总和时,给出了错误的答案。 Here are what I did respectively:
这是我分别做的:
Method 1: 方法1:
Calculate the sum in partition function: 计算分区函数中的总和:
def partition(listToSort, start, end):
global thesum
thesum = thesum+end-start
In the partition algorithm I'm using, I need to add m-1 when partitioning a m-length array. 在我使用的分区算法中,对m长度数组进行分区时需要添加m-1。
Method 2: 方法2:
calculate the sum in the recursive function qsort: 在递归函数qsort中计算总和:
def qsort(listTo, start, end):
if start >= end :
return
else:
index = partition(listTo, start, end)
qsort(listTo, start, index-1)
global thesum
thesum = thesum + index-1-start
qsort(listTo, index+1, end)
thesum = thesum + end-index-1
In this method, thesum
is not initialized to 0
but the length of the original array minus 1. 在此方法中,
thesum
未初始化为0
而是原始数组的长度减去1。
Things you may also need to know: 您可能还需要了解的事项:
The algorithm I'm implementing is a simple version of quicksort. 我正在实现的算法是quicksort的简单版本。 I have a list and need to sort it with this program.
我有一个列表,需要用此程序对其进行排序。 I use a global variable to denote the total comparisons the algorithm need to perform.
我使用全局变量来表示算法需要执行的总比较。
The problem and question 问题与疑问
I think the two methods are equivalent but they gave different answers. 我认为这两种方法是等效的,但是它们给出了不同的答案。 After some testing by printing
thesum
, I found that this global variable didn't work as expected in the function qsort
. 通过打印
thesum
进行了一些测试之后,我发现这个全局变量在函数qsort
不能正常工作。 for example when sorting a 10-elements array, thesum
was initialized to 9 but later printed out as 8, which is strange. 例如,对10个元素的数组进行排序时,
thesum
被初始化为9,但后来打印为8,这很奇怪。 But why? 但为什么? I declare it as global in the function and it's used in the same way as in the function
partition
. 我在函数中将其声明为全局函数,并以与函数
partition
相同的方式使用它。 All the difference I can think of is that qsort
is a recursive function. 我能想到的所有区别是
qsort
是一个递归函数。 But how does that make any difference? 但这有什么区别呢? So global variables are not supposed to use in recursive functions?
那么全局变量不应该在递归函数中使用吗?
这两种方法不执行等效操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.