1

在 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
4

3 回答 3

3

你的代码很好。时断言失败i==-1。在 Python 中,a[-1]是列表的最后一个元素,因此在这种情况下,您要检查第一个元素 ( a[-1+1]) 是否大于或等于最后一个元素 ( a[-1])。

于 2012-09-10T21:14:40.423 回答
0

仔细看看你在哪里插入key.

于 2012-09-10T21:13:18.543 回答
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]
于 2012-09-10T21:19:28.677 回答