[英]Order a list of numbers from given list without built-in sort, copy if first number is greater than second number swap them
我試圖實現一個 function 的方式,它與sorted(lst)
基本相同,而不使用sorted(lst)
或var = lst.copy()
但我只是不知道如何工作方式並完全遵循偽代碼中編寫的方式。
有人可以幫幫我嗎?
我的評價是:
下面是排序算法的偽代碼:
我現在的代碼:
def my_sort(lst):
lst_sorted = []
lst2 = lst.copy()
compare = True
while compare:
compare = False
num = lst2[0]
if num not in lst_sorted:
try:
for x in lst2:
if x < num:
x, num = num, x
lst_sorted.append(num)
elif num < x:
compare = True
else:
compare = True
return lst_sorted
我的教授給我的測試代碼:
def test_my_sort():
lst_test = random.choices(range(-99, 100), k=6)
lst_copy = lst_test.copy()
lst_output = my_sort(lst_test)
assert lst_copy == lst_test, "Error: my_sort (lst) changes the contents of list lst"
assert lst_output == sorted(lst_test), \
f"Error: my_sort ({lst_test}) returns {lst_output} instead of {sorted (lst_test)}"
if __name__ == '__main__':
try:
test_my_sort()
print("Your my_sort () function works fine!")
根據您使用標志compare
的意圖和確切的評估規則,這里是一步一步的解釋:
def my_sort(lst):
# We copy the list so that the changes are not made in the original variable.
# We will modify lst2 from now.
lst2 = lst.copy()
compare = True
while compare is True:
# compare will remain False as long as there is no swapping
compare=False
# We walk the list index by index, excepted the last one
# so we don't get an index error from the last "index+1"
for i in range(len(lst2)-1):
# If the first is greater than the second...
if lst2[i]>lst2[i+1]:
# We swap
bump = lst2[i]
lst2[i]=lst2[i+1]
lst2[i+1]= bump
# and set compare to True to ask for another iteration of the while loop
compare=True
return lst2
您可以換成一行:
for i in range(len(lst2)-1):
if lst2[i]>lst2[i+1]:
lst2[i], lst2[i+1] = lst2[i+1], lst2[i]
compare=True
這種排序算法稱為Bubble Sort
。
有一個優化是基於觀察到的,最大值總是在一次迭代中被帶到最后的槽。 因此,在最壞的情況下,您可以通過在每次迭代中提前停止一個索引來避免(n-1)**2
索引。
這是一個改編的實現:
def optimized_sort(lst):
lst2 = lst.copy()
compare = True
#Creating a variable to store the iteration count
n = 0
while compare is True :
compare=False
# This time, we walk from index 0 to the last index minus the iteration count
for i in range(len(lst2) - 1 - n):
if lst2[i]>lst2[i+1]:
lst2[i],lst2[i+1] = lst2[i+1], lst2[i]
compare=True
# We increment the iteration count
n += 1
return lst2
當然,這種算法仍然表現不佳,主要用於教育目的。
我只是在學習 python,但這對我有用:
def my_sort(lst):
randHolder = []
for ele in range(len(lst)):
mini = min(lst)
giveIndex = lst.index(mini)
popped = lst.pop(giveIndex)
randHolder.append(popped)
lst = randHolder
return lst
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.