[英]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 is clearly not greater than 101, so i dont know why it keeps getting swapped 9 显然不大于 101,所以我不知道为什么它一直被交换
As stated in the comments, the sorting problem comes from the fact that your input is a list of string
s and not int
s.如评论中所述,排序问题来自您的输入是
string
s 而不是int
s 的列表。 You can easily transform the values with a list comprehesion
.您可以使用
list comprehesion
轻松转换值。
Two more comments: 1) Unlike other programming languages, in python
you don't need to use a temporary variable to switch the values of two variables, and you can do it in 1 line instead of 3. 2) It's more accepted to use while True
structure without pre-defining a special variable (eg "finish") before the loop, and to use a break
clause to get out of the loop.还有两点评论:1)与其他编程语言不同,在
python
中,您不需要使用临时变量来切换两个变量的值,并且可以在 1 行而不是 3 行中完成。 2)使用起来更容易接受while True
结构没有在循环之前预先定义一个特殊的变量(例如“finish”),并使用一个break
子句来退出循环。
So here is the fixed and modified code:所以这里是固定和修改的代码:
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: 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.