【发布时间】: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