[英]Why can't I run my code? (Insertion Sort algorithm)?
def insertionSort(lst):
k = 1
while k < len(lst):
x = lst.pop(k)
insertInOrder(lst, k, x)
k += 1
def insertInOrder(lst, k, x):
while k >= 1 and lst[k-1] > x:
k -= 1
lst.insert(k, x)
這是我到目前為止所做的代碼,但是我是python的新手,無法運行它。 我是否缺少print
聲明或一套?
在insertInOrder
while
測試時,您的1st會出現輕微錯誤。 這是修復的版本。 我添加了print
呼叫,因此您可以查看排序的進度。
def insertionSort(lst):
k = 1
while k < len(lst):
x = lst.pop(k)
insertInOrder(lst, k, x)
k += 1
def insertInOrder(lst, k, x):
print(k, x, lst)
while k > 0 and lst[k-1] > x:
k -= 1
lst.insert(k, x)
a = [4, 5, 7, 2, 9]
print(a)
insertionSort(a)
print(a)
輸出
[4, 5, 7, 2, 9]
1 5 [4, 7, 2, 9]
2 7 [4, 5, 2, 9]
3 2 [4, 5, 7, 9]
4 9 [2, 4, 5, 7]
[2, 4, 5, 7, 9]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.