选择排序算法Python [英] Selection Sort Algorithm Python

查看:73
本文介绍了选择排序算法Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Working on implementing this algorithm using Python. I thought my logic was okay but apparently not as Python is complaining. The while loop is causing issues. If I remove that it works as expected but obviously doesn't sort the whole list. My thought process -> Use Linear Search to find the smallest number -> Append that new number to a list -> Remove that number from the current list -> Loop through that same list (but with smallest number removed) again -> Repeat process until we've gone through the entire list "x" number of times. "x" being equal to the length of the list. The problem I think I'm running into is that the list never gets updated every time I run through the for loop? I keep getting the error Line 21: ValueError: list.index(x): x not in list. Even though "x" is in the list. Any idea as to what I'm doing wrong?

"""
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获取的前一个值.

It looks like you're not re-initializing the smallest_number variable, so after the first execution of your while loop - you look for a value smaller than the previous value which you just poped from the list.

当找不到小于列表中不再存在的先前最小值的值时,请尝试popwhile循环的上一迭代中相同的smallest_number.但是,该值不再出现在items_to_sort列表中,这就是为什么获得ValueError

When you don't find a value smaller than the previously smallest value which is no longer in the list, you try to pop the same smallest_number as in the previous iteration of the while loop. However, that value is no longer in the items_to_sort list which is why you get the ValueError

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

Try moving the line smallest_number = items_to_sort[0] to be the first line executed in every iteration of your while loop.

这篇关于选择排序算法Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆