在 for 循环末尾的以下代码中,我使用 assert 函数来测试 a[i+1] 是否大于或等于 a[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