在for循环结尾处的下面的代码中,我使用assert函数来测试a [i + 1]是否大于或等于[i]但是我得到以下错误(在代码之后)下面)。同样在c ++中,带有以下内容的断言似乎工作正常,但在python(以下代码)中它似乎不起作用......任何人都知道为什么?
import random
class Sorting:
#Precondition: An array a with values.
#Postcondition: Array a[1...n] is sorted.
def insertion_sort(self,a):
#First loop invariant: Array a[1...i] is sorted.
for j in range(1,len(a)):
key = a[j]
i = j-1
#Second loop invariant: a[i] is the greatest value from a[i...j-1]
while i >= 0 and a[i] > key:
a[i+1] = a[i]
i = i-1
a[i+1] = key
assert a[i+1] >= a[i]
return a
def random_array(self,size):
b = []
for i in range(0,size):
b.append(random.randint(0,1000))
return b
sort = Sorting()
print sort.insertion_sort(sort.random_array(10))
错误:
Traceback (most recent call last):
File "C:\Users\Albaraa\Desktop\CS253\Programming 1\Insertion_Sort.py", line 27, in <module>
print sort.insertion_sort(sort.random_array(10))
File "C:\Users\Albaraa\Desktop\CS253\Programming 1\Insertion_Sort.py", line 16, in insertion_sort
assert a[i+1] >= a[i]
AssertionError
答案 0 :(得分:3)
你的代码很好。 i==-1
时断言失败。在Python中,a[-1]
是列表的最后一个元素,因此在这种情况下,您要检查第一个元素(a[-1+1]
)是否大于或等于最后一个元素(a[-1]
)
答案 1 :(得分:0)
仔细查看您插入key
的位置。
答案 2 :(得分:0)
这个怎么样:
import random
class Sorting:
def insertion_sort(self,a):
for i in range(1,len(a)):
key = a[i]
j = i
while j > 0 and a[j-1] > key:
a[j] = a[j-1]
j-=1
a[j] = key
return a
def random_array(self,size):
b = []
for i in range(0,size):
b.append(random.randint(0,1000))
print b
return b
sort = Sorting()
print sort.insertion_sort(sort.random_array(10))
输出:
$ ./sort.py
[195, 644, 900, 859, 367, 57, 534, 635, 707, 224]
[57, 195, 224, 367, 534, 635, 644, 707, 859, 900]