2015-04-02 72 views
1

我有下面的程序,它實現了一個排序好的包。當給出一個列表時,它按排序順序(升序)成功添加元素 。 當我使用另一個包的參數創建了一個新的分揀包時,它不是按排序順序(而是按降序排列)。見下面將元素按升序添加到排序數組中

感謝您的幫助

# Array Class 
#---------------------------------------------------- 
class Array(object):  # Represents an array. 
DEFAULT_CAPACITY = 5 
def __init__ (self, capacity, fillValue = None): 
'''Capacity = static size of array. fillValue is placed at each element''' 
    self._items = list() 
    self._capacity = capacity 
    self._logicalSize = 0 
    self._fillValue = fillValue 
    for count in range(capacity): 
     self._items.append(fillValue) 

def __getitem__(self, index): return self._items[index] 

def __setitem__(self, index, newItem):  
    self._items[index] = newItem 

# ArraySortedBag Class 
#---------------------------------------------------- 
class ArraySortedBag(object): 
'''An array-based bag implementation''' 
def __init__(self, sourceCollection = None): 
    '''Sets the initial state of self, which includes the contents 
    of sourceCollection, if it's present''' 
    self._items = Array(10) 
    self._size = 0 
    if sourceCollection: 
     for item in sourceCollection: 
      self.add(item) 

def __len__(self): return self._size 

def __iter__(self): 
    cursor = 0 
    while cursor < len(self): 
     yield self._items[cursor] 
     cursor += 1 

def add(self, item): 
    '''Adds item to self.'''   
    insertIndex = 0 

    # First found the index where the item will be inserted at 
    for i in range(self._size): 
     if self._items[i] > item: 
      insertIndex = i 
      break 
    # Then, shift items down by one position until the insertIndex, 
    for i in range (self._size, insertIndex, -1): 
     self._items[i] = self._items[i-1] 

    # Last, assign value to _items[insertIndex] 
    self._items[insertIndex] = item 
    self._size += 1 

# Test Driver 
#---------------------------------------------------- 
if __name__ == "__main__": 
b1 = ArraySortedBag([2000, 2, 1000]) 
print ("Display bag b1") 
for i in b1:    # <------ Correct order, ascending order 
    print (i) 

b2 = ArraySortedBag(b1) 
print ("\nDisplay bag b2") 
for i in b2:     # <----- Wrong order, descending order 
    print (i) 
+0

請修復您的問題代碼的縮進。 – martineau 2015-04-02 09:20:29

回答

1

在課堂ArraySortedBag的第二個實例,你逝去的排序列表。 ArraySortedBag。 init()方法使用add()方法添加項目。當添加()被稱爲項目被添加永遠不會少於現有的列表。因此insertIndex保持等於零。因此新項目被添加到列表的開頭。

# First found the index where the item will be inserted at 
for i in range(self._size): 
    if self._items[i] > item:  # item is never less than self._items[i] 
     insertIndex = i 
     break 
+0

爲什麼要添加的項目總是少於現有列表? – user1972031 2015-04-02 09:13:17

+0

如果是這樣,如何修復代碼,以便添加元素會導致升序?謝謝 - – user1972031 2015-04-02 09:15:15

+0

在添加預先排序的項目時,添加的每個項目將大於已添加到內部列表中的任何項目。 – martineau 2015-04-02 09:19:43

1

對於添加項目到一個排序列表,這樣一個維持排序的名單,我建議使用bisect library's insort_left或insort_right。

import bisect 

list = [10, 20, 30] 

bisect.insort(list, 25) 
bisect.insort(list, 15) 

print list