【问题标题】:Insertion sort in PythonPython中的插入排序
【发布时间】:2014-09-13 15:18:09
【问题描述】:

我有一个使用 Python 的家庭作业,但我遇到了大脑冻结。所以我应该使用插入排序来做 O(nˇ2) 练习。 例如,我有两个列表 [] 和 [5,8,1,1] 并且程序应该通过从第一个列表中删除并以正确的顺序将值从一个列表插入另一个列表: [][5,8,1,1] = [5][8,1,1] = [5,8][1,1] = [1,5,8][1] = [1,1, 5,8][]

我想出了一些办法,不知道我是否走在正确的轨道上,但这似乎是最合理的。缩进是有序的,但是在这里复制代码会以某种方式搞砸了。 P.S 对不起爱沙尼亚语,必须用爱沙尼亚语编写代码。

def pisteMeetod2(t2ishulk):
    tulemus = [] #new list
    hulgacopy = t2ishulk[0:len(t2ishulk)] #main list
    for el in t2ishulk: #going through first list
        if not tulemus: #if list empty (which it at the beginning is) then from here
            tulemus.append(el)
            del hulgacopy[0]
        else:
            for elemendid in tulemus: #check if there is a lower element from new list
                n = 0
                if hulgacopy[0] <= tulemus[n]:
                    tulemus.insert(n-1,el)
                    del hulgacopy[0]
                    break
                n = n + 1

所以现在我遇到了如何处理第二个循环的问题。在它完成检查结果列表中名为“tulemus”的元素之后,如果它没有找到任何匹配项,我应该如何继续我的代码,以便它将“el”附加到 tulemus。

【问题讨论】:

    标签: python insertion-sort


    【解决方案1】:

    您可以将else 子句添加到内部for 循环:

    for elemendid in tulemus: #check if there is a lower element from new list
        n = 0
        if hulgacopy[0] <= tulemus[n]:
            tulemus.insert(n, el)
            del hulgacopy[0]
            break
        n = n + 1
    else:
        tulemus.append(el)
        del hulgacopy[0]
    

    如果循环没有使用break 终止,它的主体就会被执行。您可以在 Python 的 official tutorial 中阅读有关循环中的 else 子句的更多信息。

    还请注意,如果您在迭代时找到插入点,您应该使用tulemus.insert(n, el) 而不是tulemus.insert(n-1, el) 将当前元素插入那里。否则,当n == 0 时,您最终将插入到列表末尾(索引 -1)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多