冒泡排序算法 & 'int' 对象不可订阅
Bubble Sort Alg & 'int' object is not subscriptable
我已经用了很长一段时间了,但我无法解决下面第 4 行代码中发生的错误('int' 对象不可订阅)。
我希望将 my counter 变量与数组中的前一个索引进行比较,如果前一个索引处的元素较大,则交换它们。
如有任何建议,我们将不胜感激!
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
temp = list_of_numbers[j-1]
list_of_numbers[j-1] = list_of_numbers[j]
list_of_numbers = temp
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))enter code here
行中:
list_of_numbers = temp
您正在为变量 list_of_numbers
分配一个整数,这导致了错误。
因此,请改用:
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
temp = list_of_numbers[j-1]
list_of_numbers[j-1] = list_of_numbers[j]
list_of_numbers[j] = temp
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))
或更好的变量交换:
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
list_of_numbers[j],list_of_numbers[j-1] = list_of_numbers[j-1],list_of_numbers[j]
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))
我已经用了很长一段时间了,但我无法解决下面第 4 行代码中发生的错误('int' 对象不可订阅)。
我希望将 my counter 变量与数组中的前一个索引进行比较,如果前一个索引处的元素较大,则交换它们。
如有任何建议,我们将不胜感激!
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
temp = list_of_numbers[j-1]
list_of_numbers[j-1] = list_of_numbers[j]
list_of_numbers = temp
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))enter code here
行中:
list_of_numbers = temp
您正在为变量 list_of_numbers
分配一个整数,这导致了错误。
因此,请改用:
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
temp = list_of_numbers[j-1]
list_of_numbers[j-1] = list_of_numbers[j]
list_of_numbers[j] = temp
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))
或更好的变量交换:
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
list_of_numbers[j],list_of_numbers[j-1] = list_of_numbers[j-1],list_of_numbers[j]
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))