在下面的for循環結束處的代碼中,我使用assert函數來測試[i + 1]是否大於或等於[i],但我得到以下錯誤(在下面的代碼之後)。同樣在C++中,assert與以下似乎工作得很好,但在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
有一個流浪')'你的斷言線收小括號,應該說是嗎? –
不,對不起,我已經修復了......它仍然無法工作。 – user1661211