使用合并函数计算版本算法

时间:2018-05-17 05:30:54

标签: python algorithm inversion

我试图编码计数版本算法的最佳版本。 我在第84行遇到了这个错误:int对象不可迭代。

但我无法弄清楚为什么我会遇到这个问题。

函数mergesort:按递增顺序合并一个数字列表(当我单独使用它时,这个工作正常)

函数merge_and_count:在输入中取两个合并数组,并计算左数组中大于右数组元素的元素数

函数sort_and_count:将给出反转次数的函数(它还返回一个列表,因为它允许我使用递归)

以下是代码:

def mergesort(list):
    """Fonction qui classe les nombres de la liste par ordre croissant.
        Celle la fonctionne bien et renvoie une liste"""
    taille = len(list)
    liste_1_temp = []
    liste_2_temp = []


    if len(list) > 1:

        for i in range(0,(taille//2)):
            liste_1_temp.append(list[i])

        for i in range((taille//2),taille):
            liste_2_temp.append(list[i])
        mergesort(liste_1_temp)
        mergesort(liste_2_temp)

        i = 0
        j = 0
        k = 0
        while i < len(liste_1_temp) and j < len(liste_2_temp):
            if liste_1_temp[i] < liste_2_temp[j]:
                list[k] = liste_1_temp[i]
                i+=1
                k+=1
            else:
                list[k] = liste_2_temp[j]
                j += 1
                k+=1
        while (i < len(liste_1_temp)):
            list[k] = liste_1_temp[i]
            i+=1
            k+=1

        while (j < len(liste_2_temp)):
            list[k] = liste_2_temp[j]
            j+=1
            k+=1
    liste_finale = list
    return liste_finale



def merge_and_count(A,B):
    """Fonction qui doit renvoyer """

    i = 0
    j = 0
    count = 0
    C = []

    while (i < len(A)):
        if A[i] > B[j]:
            C.append(B[j])
            count += (len(A)-i)
            i = 0
            j += 1
        else:
            C.append(A[i])
            i += 1
    return count,C



def sort_and_count(L):

    i = 0
    A = []
    B = []

    if len(L) == 1:
        return 0

    else:
        size = len(L)
        size2 = len(L) // 2

        for i in range(0, size2):
            A.append(L[i])
        for i in range(size2,size-1):
            B.append(L[i])

        (rA,A) = sort_and_count(A)
        (rB,B) = sort_and_count(B)
        (r,L) = merge_and_count(mergesort(A),mergesort(B))

        return ((rA+rB+r),L)

1 个答案:

答案 0 :(得分:0)

您忘了在sort_and_count返回一对:

def sort_and_count(L):

    i = 0
    A = []
    B = []

    if len(L) == 1:
        return 0  # <-- You forgot to return the list as second element
    ...
    ...

由于这些行

    (rA,A) = sort_and_count(A)
    (rB,B) = sort_and_count(B)

期望赋值运算符右侧有一个iterable,只得到一个整数,你得到 int对象不可迭代错误。

相关问题