【问题标题】:TypeError: 'NoneType' - Selection Sort on PythonTypeError:'NoneType' - Python 上的选择排序
【发布时间】:2018-03-17 14:01:07
【问题描述】:

我正在尝试使用 python 进行选择排序,我最近刚刚在“Python Crash Course”这本书之后学习了 python,然后我正在阅读“grokking algorithm”这本书

我非常了解选择排序算法,但我就是不明白为什么我会得到 TypeError: 'NoneType' object cannot be interpreted as an integer

所以我测试它的方法是使用random.randint(1, 101)range(0,11) 填充我的数组,我不明白为什么python 不能将它解释为整数?因为这两个函数都返回一个整数。当我执行new_array.append(arr.pop(smallest)) 时似乎发生了错误。

请参阅下面的完整代码。 (我使用的是 Python 3)

import random

def find_smallest(arr):
    """Return the index of the smallest value in an array"""
    smallest = arr[0]
    smallest_index = 0

    for i in range(1, len(arr)):
        if arr[i] < smallest:
            smallest = arr[i]
            smallest_index = i
        return smallest_index

def selection_sort(arr):
    """sort an array by storing smallest value to new array 1 by 1"""
    new_array = []
    for i in range(len(arr)):
        smallest = find_smallest(arr)
        new_array.append(arr.pop(smallest))
    return new_array


my_array = []
for i in range(0, 11):
    my_array.append(random.randint(1, 101))
    print(my_array[i])

sorted_array = selection_sort(my_array)
for i in range(len(sorted_array)):
    print(sorted_array[i])

【问题讨论】:

    标签: python-3.x algorithm sorting


    【解决方案1】:

    您的 find_smallest() 函数中似乎存在缩进问题

    考虑

    def find_smallest(arr):
        """Return the index of the smallest value in an array"""
        smallest = arr[0]
        smallest_index = 0
    
        for i in range(1, len(arr)):
            if arr[i] < smallest:
                smallest = arr[i]
                smallest_index = i
        return smallest_index  # <--- this is the line
    

    请注意,return 语句的缩进与您的代码不同。

    要调试此类问题,您应该注意到arr.pop() 需要一个整数或整数列表作为参数,因此您可以插入

     assert(smallest is not None)
    

    在失败行 new_array.append(arr.pop(smallest)) 上方并确认触发了断言,然后检查发生这种情况的迭代将断言语句替换为

     assert(smallest is not None), "Array length is %d" % len(arr)
    

    这会触发异常

     AssertionError: Array length is 1
    

    然后你会知道你需要检查你的find_smallest函数在它的参数是一个长度为1的数组时返回什么。

    【讨论】:

    • 非常感谢!我现在明白了,因为 return 语句的缩进错误,脚本的工作方式是它只会在满足“if 语句”时返回。谢谢,我很欣赏你如何包含此类问题的调试步骤。你太棒了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2013-01-19
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多