【问题标题】:ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (0,)ValueError:形状为 (1,) 的不可广播输出操作数与广播形状 (0,) 不匹配
【发布时间】:2019-12-26 18:25:23
【问题描述】:

我正在尝试理解 mergeSort 算法并运行此链接 (https://medium.com/@ssbothwell/counting-inversions-with-merge-sort-4d9910dc95f0) 上提供的代码

但是,我收到错误 ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (0,)

我无法理解为什么会发生这种情况,因为代码适用于较小的示例,例如 arr = [1, 20, 6, 4, 5]。 (数组测试包含50个随机数)

谁能解释我做错了什么?当我们得到形状(0,)时,有人也可以解释一下吗?是不是数组为空的时候?

test = numbers[0:50]

def mergeSortInversions(arr):
    if len(arr) == 1:
        return arr, 0
    else:
        mid = len(arr)//2
        a = arr[:mid]
        b = arr[mid:]
        a, ai = mergeSortInversions(a)
        b, bi = mergeSortInversions(b)
        c = []
        i = 0
        j = 0
        inversions = 0 + ai + bi
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            c.append(a[i])
            i += 1
        else:
            c.append(b[j])
            j += 1
            inversions += (len(a)-i)
    c += a[i:]
    c += b[j:]
    return c, inversions

arr = [1, 20, 6, 4, 5] 
#print('test', np.shape(test))
x, inv = mergeSortInversions(test)    
print(inv)

【问题讨论】:

    标签: python arrays algorithm sorting mergesort


    【解决方案1】:

    好的,我想通了,您不能将元素添加到空数组中。

    我使用条件解决了它

    if len(a[i:]) != 0:
       c += a[i:]
    
    

    【讨论】:

      猜你喜欢
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 2020-03-07
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多