我目前正在使用离散结构和算法,并且必须第一次使用python。
我在语法上遇到了一些麻烦,并且在气泡排序和插入排序函数打印方面遇到了问题
def insertion_sort(numbers):
numbers = [1, 5, 9, 3, 4, 6]
for index in range(1, len(numbers)):
value = numbers[index]
i = index - 1
while i >= 0:
if value < numbers[i]:
numbers[i+1] = numbers[i]
numbers[i] = value
i = i - 1
print(numbers)
else:
break
def bubble_sort(numbers):
for i in range(0, len(numbers) - 1, 1):
for j in range(0, len(numbers) - 1 - i, 1):
if numbers[j] < numbers[j + 1]:
temp = numbers[j]
numbers[j] = numbers[j + 1]
numbers[j + 1] = temp
numbers = [1, 5, 9, 3, 4, 6]
print(numbers)
答案 0 :(得分:0)
numbers
参数。因此,您需要使用数字列表作为输入来调用它们。例如。 insertion_sort([1, 5, 9, 3, 4, 6])
numbers
列表参数并对它进行排序。为了从函数外部访问结果,您需要在每个函数的末尾添加return numbers
。 总而言之,您的代码应如下所示:
def insertion_sort(numbers):
for index in range(1, len(numbers)):
value = numbers[index]
i = index - 1
while i >= 0:
if value < numbers[i]:
numbers[i+1] = numbers[i]
numbers[i] = value
i = i - 1
else:
break
return numbers
def bubble_sort(numbers):
for i in range(0, len(numbers) - 1, 1):
for j in range(0, len(numbers) - 1 - i, 1):
if numbers[j] < numbers[j + 1]:
temp = numbers[j]
numbers[j] = numbers[j + 1]
numbers[j + 1] = temp
return numbers
numberstosort = [1, 5, 9, 3, 4, 6]
print(insertion_sort(numberstosort))
print(bubble_sort(numberstosort))
这将打印每个功能的输出。输出:
[1, 3, 4, 5, 6, 9]
[9, 6, 5, 4, 3, 1]