python - 选择排序算法Python

标签 python algorithm list sorting

致力于使用 Python 实现此算法。我认为我的逻辑没问题,但显然不像 Python 所提示的那样。 while 循环导致问题。如果我删除它,它会按预期工作,但显然不会对整个列表进行排序。我的思考过程 -> 使用线性搜索找到最小的数字 -> 将该新数字附加到列表 -> 从当前列表中删除该数字 -> 再次循环遍历相同的列表(但删除最小的数字) -> 重复过程直到我们遍历整个列表“x”次。 “x”等于列表的长度。我认为我遇到的问题是每次运行 for 循环时列表都不会更新?我一直收到错误 Line 21: ValueError: list.index(x): x not in list。 即使“x”在列表中。知道我做错了什么吗?

"""
Selection sort algorithm.
"""

import random
ls = []
max_number = 10
while len(ls) < max_number:
    ls.append(random.randint(1,101))
print ls   

def selection_sort(items_to_sort):
    smallest_number = items_to_sort[0]
    current_number = 0
    sorted_items = []
    item_len = len(items_to_sort)
    while item_len > 0:
        for item in items_to_sort[:]:
            if item < smallest_number:
                smallest_number = item
        items_to_sort.pop(items_to_sort.index(smallest_number))    
        sorted_items.append(smallest_number)   
        item_len -= 1    
    return sorted_items
print selection_sort(ls)

最佳答案

看起来您没有重新初始化 smallest_number 变量,所以在第一次执行您的while 循环后 - 您看对于小于您刚刚从列表中弹出的先前值的值。

当你没有找到比列表中不再存在的先前最小值更小的值时,你尝试pop与先前相同的smallest_number while 循环的迭代。但是,该值不再在 items_to_sort 列表中,这就是您得到 ValueError

的原因

尝试将 smallest_number = items_to_sort[0] 行移动到 while 循环的每次迭代中执行的第一行。

关于python - 选择排序算法Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39843663/

相关文章:

python - 转置子列表中的元素

python - Scrapy 如何从多个页面抓取项目?

python - (R-->R) 函数的简单自动分类

python - 如何使变量等于 Python 列表中的字符串之一

algorithm - Puyo Puyo游戏如何实现AI?

python - 为什么我的 Iterative Deepening Depth-First Search 实现占用的内存与 BFS 一样多?

Python 将排序的字典转换为列表?

Python 正则表达式 - 命名组不完全匹配

python - 计算 Pandas 列中的日期列表

python - 检查日期是否在字符串中