我正在编写一个简单的递归排序代码,并在 Python 2.7.6
和 Python 3.3.3
中对其进行了测试。但是我得到了两个不同的结果。代码如下。
import math, copy, random, sys
call_count = 0; # Keep track of number of times of stooge_sort() get called
swap_count = 0; # Keep track of number of times swapping.
def stooge_sort(a, origin):
global call_count, swap_count;
call_count += 1;
n = len(a);
m = int(math.ceil(n*2/3));
if(n == 2 and a[0] > a[1]):
a[0], a[1] = a[1], a[0];
swap_count += 1;
elif (n > 2):
first = copy.deepcopy(a[0:m]);
a[0:m] = stooge_sort(first, origin);
second = copy.deepcopy(a[n-m:]);
a[n-m:] = stooge_sort(second, origin);
first = copy.deepcopy(a[0:m]);
a[0:m] = stooge_sort(first, origin);
return a;
a = [int(random.random() * 100) for i in range(10)];
stooge_sort(a, a);
print("sort function call count = " + str(call_count))
print("swap count = " + str(swap_count));
1) 如果我在 Python 2.7.6
中运行,我会得到不正确的排序并且
sort function call count = 40
swap count = 2
2) 如果我在 Python 3.3.3
中运行,我得到正确的排序并且
sort function call count = 364
swap count = 18
所以我想知道 Python 2.7.6
是哪一部分出错了?
最佳答案
都是因为这条线
m = int(math.ceil(n*2/3));
在 Python 2 中,n*2/3
给出一个比实际值小 1 的值,因为浮点值被截断了 (since /
does floor division in Python 2.x),但在 Python 3 中,它将进行适当的浮点除法。
要使程序运行一致,只需确保您使用的是 float
m = int(math.ceil(n*2.0/3.0))
关于python - 来自 python 2.7.6 和 3.3.3 的不同递归结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22271139/