【问题标题】:Median of sorted arrays of equal length等长排序数组的中位数
【发布时间】:2020-11-18 21:06:35
【问题描述】:

我正在尝试找到两个相同长度的排序数组的中位数,我正在使用分治算法。但是我的代码返回 None 而不是一个值 这是查找单个数组中位数的代码:

def getmedian(li):
    x = len(li)
    if x%2 == 0:
        return (li[x//2] + li[(x//2)-1])/2
    else:
        return li[(len(li)-1)//2]

然后我对两个数组使用以下函数:

def TwoList(list1,list2):
    if len(list1) == 1:
        return (list1[0] + list2[0])/2
    elif len(list2)== 2:
        return (max(list1[0],list2[0]) + min(list2[1], list1[1]))/2
    else:
        #pdb.set_trace()
        x = getmedian(list1)
        y = getmedian(list2)
        if x == y:
            return x
        elif x > y:
            if len(list1)%2==0:
                TwoList(list1[:len(list1)//2], list2[len(list1)//2:])
            else:
                TwoList(list1[:len(list1)//2+1], list2[len(list1)//2:])
        else:
            if len(list1)%2==0:
                TwoList(list1[len(list1)//2:], list2[:len(list1)//2])
            else:
                TwoList(list1[len(list1)//2:], list2[:len(list1)//2+1])

【问题讨论】:

    标签: python-3.x median divide-and-conquer


    【解决方案1】:

    看起来你做对了,除了在TwoList递归调用中返回值。
    请看下面的代码,在你必须return值的地方注释。

    def getmedian(li):
        x = len(li)
        if x%2 == 0:
            return (li[x//2] + li[(x//2)-1])/2
        else:
            return li[(len(li)-1)//2]
    
    def TwoList(list1,list2):
        if len(list1) == 1:
            return (list1[0] + list2[0])/2
        elif len(list2)== 2:
            return (max(list1[0],list2[0]) + min(list2[1], list1[1]))/2
        else:
            #pdb.set_trace()
            x = getmedian(list1)
            y = getmedian(list2)
            if x == y:
                return x
            elif x > y:
                if len(list1)%2==0:
                    return TwoList(list1[:len(list1)//2], list2[len(list1)//2:]) # return value
                else:
                    return TwoList(list1[:len(list1)//2+1], list2[len(list1)//2:]) # return value
            else:
                if len(list1)%2==0:
                    return TwoList(list1[len(list1)//2:], list2[:len(list1)//2]) # return value
                else:
                    return TwoList(list1[len(list1)//2:], list2[:len(list1)//2+1]) # return value
    
    print(TwoList([1,2,3,4],[5,6,7,8]))
    

    【讨论】:

    • @DhruvMakwana 很高兴为您提供帮助 :-)
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 2018-06-28
    • 1970-01-01
    • 2013-09-18
    • 2011-09-05
    • 2020-11-08
    • 1970-01-01
    相关资源
    最近更新 更多