【问题标题】:Numpy bubblesort not printing sorted arrayNumpy bubblesort 不打印排序数组
【发布时间】:2022-10-23 21:12:29
【问题描述】:

我怎样才能弄清楚为什么我的冒泡排序没有打印?我也使用了 Numpy:

number = int(input('Tell the AI the size of the array ==> '))
            arr = np.random.rand(number)
            def Bubblesort(arr):
                for i in range(len(arr)):
                    for j in range(0, len(arr)):
                        if arr[j] > arr[j + 1]:
                            temp = arr[j]
                            arr[j] = arr[j + 1]
                            arr[j + 1] = temp
                    Bubblesort(arr)
                    print(arr)
        

我是初学者,我真的需要这个项目。

【问题讨论】:

  • 你的缩进全错了;不清楚您的代码是否真的是这样,或者您是否搞砸了复制+粘贴。您必须了解,在 Python 中,缩进是代码的关键核心组件,它决定了什么代码在什么时间运行。因此,您的问题可能完全是因为缩进,但在您修复它之前我们无法知道。
  • 也就是说,看起来您的Bubblesort(arr) 和print(arr) 行被缩进到Bubblesort 的范围内。这意味着您的代码只定义了Bubblesort,但它没有称呼代码。因此,您的程序将在您输入arr 的长度时结束,因为在那之后没有任何代码可以执行任何操作。

标签: python arrays numpy sorting bubble-sort


【解决方案1】:

有两个问题。一、Bubblesort(arr)和print(arr)的缩进错误;它被认为是内Bubblesort(),这意味着实际上从来没有任何代码叫Bubblesort()。因此,您的程序将在您输入arr 长度的那一刻结束。

此外,一旦我解决了这个问题,你的程序就开始给出关于数组索引超出范围的错误:

    if arr[j] > arr[j + 1]:
IndexError: index 10 is out of bounds for axis 0 with size 10

这是因为您的代码索引arr[j + 1],但它会循环直到arr 的长度,这意味着您将索引一个项目超过arr 的结尾。为了修复它,你只需要循环直到比arr 的长度小一。所以,我只是将for j in range(0, len(arr)) 更改为for j in range(0, len(arr) - 1)。

因此,在固定以及缩进的情况下,您的代码实际上可以正常工作:

import numpy as np

number = int(input('Tell the AI the size of the array ==> '))
arr = np.random.rand(number)


def Bubblesort(arr):
    for i in range(len(arr)):
        for j in range(0, len(arr) - 1):
            if arr[j] > arr[j + 1]:
                temp = arr[j]
                arr[j] = arr[j + 1]
                arr[j + 1] = temp


Bubblesort(arr)
print(arr)

输出:

Tell the AI the size of the array ==> 10
[0.07201946 0.20971682 0.26190436 0.4245566  0.48094863 0.50693179
 0.52760367 0.82474669 0.86552769 0.90142202]

【讨论】:

    【解决方案2】:

    由于压痕,它可能无法打印。对 Bubblesort(arr) 的调用在函数的定义中。尝试移动它以与“def”对齐

        number = int(input('Tell the AI the size of the array ==> '))
        arr = np.random.rand(number)
        def Bubblesort(arr):
            for i in range(len(arr)):
                for j in range(0, len(arr)):
                    if arr[j] > arr[j + 1]:
                        temp = arr[j]
                        arr[j] = arr[j + 1]
                        arr[j + 1] = temp
        Bubblesort(arr)
        print(arr)
    

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 2023-03-28
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      相关资源
      最近更新 更多