【发布时间】:2016-04-21 20:44:09
【问题描述】:
我正在学习编程课程(我是一个完全的初学者),当前的任务是创建一个 Python 脚本,该脚本可以在不使用“sorted”等内置函数的情况下按升序对数字列表进行排序.
我开始想出的脚本可能是可笑的复杂和低效,但我想尝试让它最终工作。换句话说,我不想只是复制别人更好的脚本。
此外,据我所知,这个脚本(如果它曾经运行过的话)可能只是将事物置于一个不一定是升序的新顺序中。不过,这只是一个开始,希望我稍后会解决这个问题。
无论如何,我在当前的版本中遇到了几个问题,最新的是它永远运行而没有打印任何东西。
就是这样(用散列解释我想要完成的事情)。如果有人可以查看它并告诉我为什么代码与我对每个块应该做什么的解释不符,那就太好了!
# The numbers to be inputted, could be anything
numList = [1, 25, 5, 6, 17, 4]
# The final (hopefully sorted) list
numSort = []
# The index
i = 0
# Run the loop until you run out of numbers
while len(numList) != 0:
# If there's only one value left in numList,
# attach it to the end of numSort.
# (Variable 'basket' is just for transporting numbers)
if len(numList) == 1:
basket = numList.pop()
numSort.append(basket)
# The rest of the elifs are supposed to compare values
# that sit next to each other.
# If there's still a number in numList after 'i'
# and 'i' is smaller than that next number
# then pop 'i' and attach it to the end of numSort
elif numList[i+1] != numList[-1] and numList[i] < numList[i+1]:
basket = numList.pop(i)
numSort.append(basket)
# If there's NOT a number after 'i'
# then compare 'i' to the first number in the list instead.
elif numList[i+1] == numList[-1] and numList[i] < numList[0]:
basket = numList.pop(i)
numSort.append(basket)
# If 'i' IS the last number in the list
# and has nothing to compare itself to,
# Then start over and go through it again
# from the beginning
elif numList [i+1] == numList[-1]:
i = 0
# If 'i' is not at the end of numList yet
# and 'i' is NOT smaller than the next number
# and there are still numbers left
# then move on to the next pair
# and continue comparing and moving numbers
else:
i = i+1
# Hopefully these will be in ascending order eventually.
print(numSort)
【问题讨论】:
-
已经,您可以将
while len(numList) != 0:替换为while numList: -
我看到的第一个语义错误是
numList [i+1] == numList[-1]。这不检查位置i的数字是否是列表的最后一个数字,它检查位置i+1的数字是否等于 到列表的最后一个数字。 -
可能首先使用数组,然后尝试了解 numList[-1] 的作用。
-
实现其他算法有什么问题吗?比如冒泡排序、选择排序等等……这些都很简单,实现起来也很简单,而且需要的代码也少得多。
-
当您使用
pop时,索引再次从零开始,因此您将在此行elif numList[i+1] != numList[-1] and numList[i] < numList[i+1]上获得index error
标签: python list sorting python-3.x