我是python的新手,为了更好,我买了一些教科书。我在教科书中发现的一个问题让我非常困惑,因为我觉得解决办法是显而易见的。我得到了一个插入排序代码,它按升序排列列表。这个问题要求在不使用内置函数而是改变代码的情况下反转列表的顺序(因此它是降序的)。代码如下:
sequence = [5,-2,0,6,10,-5,1]
def myInsertionSort(sequence):
for i in range (1, len(sequence)):
item = sequence[i]
j = i
while j > 0 and sequence[j-1] > item:
sequence[j] = sequence[j-1]
j -= 1
sequence[j] = item
return sequence
myInsertionSort(sequence)
我添加了一个示例序列,这里的输出是它按升序排列序列。我意识到这里的关键是理解代码,所以我用了pythontutor.com为了可视化和理解每一步,即使我现在觉得我理解了它,我对代码所做的每一次编辑都会导致一个错误或无序列表。你知道吗
考虑一下您的代码的这个小小的泛化;我刚刚将
sequence[j-1]
和item
的比较重构为一个单独的函数。你知道吗while
循环交换两个被认为是无序的项。现在想一想,如果通过修改out_of_order
的定义来改变两个项目无序的含义,会发生什么。你知道吗你的书例不太像Python。你知道吗
这称为插入排序。这可能有助于了解它如何与动画一起工作。看看这个网站(确保选择插入[INS]排序):https://visualgo.net/bn/sorting
也就是说,密切关注while循环语句
sequence[j-1] > item
中的>
。这是我的暗示。你知道吗如果让它更容易阅读,这里有一个例子写得有点不同:
一个超级简单的方法是简单地返回序列[::-1],它将为您提供一个升序列表。我不认为列表反转技术是内置函数。你知道吗
但如果你认为这很重要,这里有一个替代代码:
相关问题 更多 >
编程相关推荐