【问题标题】:Insertion sort invariant assertion fails插入排序不变断言失败
【发布时间】:2012-09-10 21:01:05
【问题描述】:

在 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

【问题讨论】:

  • 在你的断言行上有一个流浪的)关闭括号,应该在那里吗?
  • 不,抱歉,我已经修复了这个问题......它仍然无法正常工作。

标签: python sorting assert insertion-sort


【解决方案1】:

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

【讨论】:

  • 谢谢,这帮助很大!
【解决方案2】:

仔细查看您插入 key 的位置。

【讨论】:

    【解决方案3】:

    这个怎么样:

    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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-24
      • 2011-05-27
      • 1970-01-01
      • 2021-10-19
      • 2021-03-16
      • 2010-09-26
      • 2018-11-09
      相关资源
      最近更新 更多