2015-10-12 3 views
0

Эта сортировка сортировки сортирует все элементы, кроме последних. Это очень странно. Bc У меня есть идентичная функция, которая сортирует ВСЕ элементы по другому атрибуту. Я пытался копировать, вставлять и изменять рабочую функцию, но это казалось бесполезным.Вставка сортировка пропускает последний элемент

for i in range(1, len(metals)): 
    index = i 
    while index != 0 and metals[index].weightPerBar > metals[index - 1].weightPerBar: 
     metals[index], metals[index - 1] = metals[index - 1], metals[index] 
     index -= 1 

Благодаря

Heres остальные модуля:

class Metal(struct): 
     """ 
     Represents a single metal type, composed of: 
     :slot name (str): The name of the metal 
     :slot totalBars (int): The total number of bars 
     :slot weightPerBar (int): The weight of a single bar 
     :slot valuePerBar (int): The value of a single bar 
     :slot valuePerWeight (float): The value per weight of the metal 
     :slot barsTaken (int): The number of bars added to the satchel 
     """ 
     _slots = ((str, "name"), (int, "totalBars"), (int, "weightPerBar"), (int, "valuePerBar"), (float, "valuePerWeight"), (int, "barsTaken")) 

     pass 


    def createMetal(name, totalBars, weightPerBar, valuePerBar): 
     """ 
     Create and return a new Metal object. 
     :param name (str): The name of the metal 
     :param totalBars (int): The total number of bars 
     :param weightPerBar (int): The weight of a single bar 
     :param valuePerBar (int): The value of a single bar 
     :return: A newly initialized Metal object 
     :rtype: Metal 
     """ 

     new_metal = Metal(name, totalBars, weightPerBar, valuePerBar) 
     return new_metal 

     pass 

    def readMetals(fileName): 
     """ 
     Read the metals from a file whose format is: 
      metalName totalBars weightPerBar valuePerBar 
     :param fileName (str): The name of the file 
     :return: A list of Metal objects 
     :rtype: list 
     """ 
     metal_list = [] 
     file = open(fileName) 
     for line in file: 
      line = line.split() 
      weight_per_bar = float(line[3])/float(line[2]) # creating derived value 
      new_metal = Metal(line[0], int(line[1]), int(line[2]), int(line[3]), weight_per_bar, 0) 

      metal_list += [new_metal] 
     return metal_list 

     pass 


    def sortMetalsByValuePerBar(metals): 
     """ 
     Sort the metals by value per bar using insertion sort. The list of 
     metals is modified in place to be ordered by value per bar. 
     :param metals (list of Metal): The list of metals 
     :return: None 
     :rtype: NoneType 
     """ 

     for i in range(1, len(metals)): 
      index = i 
      while index != 0 and metals[index].valuePerBar > metals[index - 1].valuePerBar: 
       metals[index], metals[index - 1] = metals[index - 1], metals[index] 
       index -= 1 


     pass 

    def sortMetalsByValuePerWeight(metals): 
     """ 
     Sort the metals by value per weight using insertion sort. The list of 
     metals is modified in place to be ordered by value per weight. 
     :param metals (list of Metal): The list of metals 
     :return: None 
     :rtype: NoneType 
     """ 
     for i in range(1, len(metals)): 
      index = i 
      while index != 0 and metals[index].weightPerBar > metals[index - 1].weightPerBar: 
       metals[index], metals[index - 1] = metals[index - 1], metals[index] 
       index -= 1 
     pass 

ответ

0

Ваш код прекрасно работает на моей машине, но почему вы реализующей алгоритм сортировки по своему усмотрению? Вы можете просто использовать:

metals.sort (ключ = лямбда-металл: metal.weightPerBar, реверс = True)

+0

Когда он сортирует [150, 400, 125, 166] как [166, 150, 125, 400] – matttm

+0

weight_per_bar = int (строка [3])/int (строка [2]) # создание производного значения new_metal = Металл (строка [0], int (строка [1]), int (строка [2]), int (строка [3]), float (weight_per_bar), 0) – matttm

+0

Тем не менее, вы не дали мне достаточно чтобы определить, где ваша проблема. Тем не менее, ваш код является безупречной реализацией сортировки вставки, когда я заменяю металлы [index] .weightPerBar на металлы [index] и металлы [index-1] .weightPerBar с металлами [index-1] и принимают металлы как массив или целые числа. Это означает, что ваша проблема должна лежать в другом месте, и я не могу ее решить, не получая больше кода. – dorverbin

1

Он должен работать, если .weightPerBar все того же типа и числовые (не строки или другие объекты). Если вес представляет собой строку, это может иметь ситуацию, когда «2», «6», «4», «10» сортируется как «6», «4», «2», «10». Вместо 10, 6, 4, 2 по желанию.

+0

Я заставил класс бросить как ints – matttm

Смежные вопросы