[英]sorting algorithm doesn't produce correct output
def sort(nums):
finish = False
while finish == False:
finish = True
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
t = nums[i]
nums[i] = nums[i+1]
nums[i+1] = t
finish = False
print(nums)
return nums
9 顯然不大於 101,所以我不知道為什么它一直被交換
如評論中所述,排序問題來自您的輸入是string
s 而不是int
s 的列表。 您可以使用list comprehesion
輕松轉換值。
還有兩點評論:1)與其他編程語言不同,在python
中,您不需要使用臨時變量來切換兩個變量的值,並且可以在 1 行而不是 3 行中完成。 2)使用起來更容易接受while True
結構沒有在循環之前預先定義一個特殊的變量(例如“finish”),並使用一個break
子句來退出循環。
所以這里是固定和修改的代碼:
def sort(nums):
nums = [int(n) for n in nums] #This is the neccesary line to fix the bug you are having
while True:
finish = True
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
nums[i], nums[i+1] = nums[i+1], nums[i]
finish = False
print(nums)
if finish:
break
return nums
l = ['1', '101', '9', '808', '54']
sort(l)
Output:
[1, 9, 101, 808, 54]
[1, 9, 101, 54, 808]
[1, 9, 54, 101, 808]
Out[17]:
[1, 9, 54, 101, 808]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.