python - 来自 python 2.7.6 和 3.3.3 的不同递归结果

标签 python algorithm sorting

我正在编写一个简单的递归排序代码,并在 Python 2.7.6Python 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/

相关文章:

swift - 按日期排序 HealthKit 数据

python - Gunicorn 和 Supervisor 错误文件没有可执行权限

不清除屏幕的 Python 诅咒

php - 投票加权算法

python - Pandas 数据帧 : Sort list column in dataframe

mysql - 在超大 MYSQL 表中查找 varchar 列的不同值

python - coverage.py 给出 "No source for code",尽管 .coveragerc 似乎告诉它代码在哪里

python - 带有分类/错误分类实例数量的混淆矩阵(Python/Matplotlib)

algorithm - 编译器的 Big-O

c# - 如何使用蒙特卡洛方法搜索极限概率