2016-10-04 90 views
0

使用Python来实现此算法。我认为我的逻辑没问题,但显然不像Python抱怨的那样。 while循环导致问题。如果我删除它按预期工作,但显然不排序整个列表。我的思考过程 - >使用线性搜索查找最小号码 - >将新号码追加到列表中 - >从当前列表中删除该号码 - >再次循环同一个列表(但删除了最小号码) - >重复处理直到我们完成整个列表“x”的次数。 “x”等于列表的长度。我想我遇到的问题是,每次运行for循环时都不会更新列表?我不断收到错误Line 21: ValueError: list.index(x): x not in list。 即使“x”在列表中。任何想法,我做错了什么?选择排序算法Python

""" 
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) 

回答

2

看起来你不重新初始化smallest_number变量,所以你while循环的第一次执行后 - 你找好于前值,你只是pop Ed来自小的值名单。

如果找不到比之前最小的值不再在列表中的值,则尝试pop与上一次while循环中的smallest_number相同。然而,该值是在items_to_sort列表不再这就是为什么你会得到ValueError

尝试移动线smallest_number = items_to_sort[0]在你的while循环的每次迭代执行的第一线。

+0

是u的权利,如果他不重新初始化smallst_number,他永远无法找到一个小数目比过去的小最小的数字... – Acepcs

+0

太棒了。你是男人中的上帝。谢谢你好,先生/女士。 – terratunaz

+0

很高兴我可以帮助,如果这个答案帮助你应该将其标记为已接受。 :) – ctj232

1

每while循环后,应先分配给items_to_sort[0]smallest_number

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