标签:包含 play 数据类型 有序 定位 链表实现 ons pyhon get
|   #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie 
 from abstractcollection import AbstractCollection 
 
 class AbstractList(AbstractCollection): """An abstract list implementation.""" 
 def __init__(self, sourceCollection): """Maintains a count of modifications to the left.""" self._modCount = 0 AbstractCollection.__init__(self, sourceCollection) 
 def getModCount(self): """Returns the count of modifications to the list.""" return self._modCount 
 def incModCount(self): """Increment the count of modifications.""" self._modCount += 1 
 def index(self, item): """Precondition: the item is in the list. Return the position of the item. Raise: ValueError if item isn‘t in the list""" position = 0 for data in self: if data == item: return position else: position += 1 if position == len(self): raise ValueError(str(item) + " not in list.") 
 def add(self, item): """Add the item to the end of the list.""" self.insert(len(self), item) 
 def remove(self, item): """Precondition: the item is in the list. Raise: ValueError is item isn‘t in the list. PostCondition:item is removed from self.""" position = self.index(item) self.pop(position)  | 
|   #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie 
 from abstractcollection import AbstractCollection 
 
 class AbstractList(AbstractCollection): """An abstract list implementation.""" 
 def __init__(self, sourceCollection): """Maintains a count of modifications to the left.""" self._modCount = 0 AbstractCollection.__init__(self, sourceCollection) 
 def getModCount(self): """Returns the count of modifications to the list.""" return self._modCount 
 def incModCount(self): """Increment the count of modifications.""" self._modCount += 1 
 def index(self, item): """Precondition: the item is in the list. Return the position of the item. Raise: ValueError if item isn‘t in the list""" position = 0 for data in self: if data == item: return position else: position += 1 if position == len(self): raise ValueError(str(item) + " not in list.") 
 def add(self, item): """Add the item to the end of the list.""" self.insert(len(self), item) 
 def remove(self, item): """Precondition: the item is in the list. Raise: ValueError is item isn‘t in the list. PostCondition:item is removed from self.""" position = self.index(item) self.pop(position)  | 
|   #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie 
 from node import TwoWayNode from abstractlist import AbstractList from linkedlistiterator import LinkedListIterator 
 
 class LinkedList(AbstractList): """A link-based list implementation""" 
 def __init__(self, sourceCollection=None): """Sets the initial state of self, which includes the contents of sourceCollection, if it‘s present.""" self._head = TwoWayNode(None) self._head.previous = self._head.next = self._head AbstractList.__init__(self, sourceCollection) 
 # Helper method returns node at position i def _getNode(self, i): """Helper method: returns a pointer to node at position i.""" if i == len(self): # Constant-time access to head node. return self._head if i == len(self) - 1: # or last data node return self._head.previous probe = self._head.next while i > 0: probe = probe.next i -= 1 return probe 
 # Accessor method def __iter__(self): """Support iteration over a view of self.""" cursor = self._head.next while cursor != self._head: yield cursor.data cursor = cursor.next 
 def __getitem__(self, i): """Precondition: 0<= i < len(self) Return the item at position i. Raises: IndexError""" 
 if i < 0 or i >= len(self): raise IndexError("List out of range.") return self._getNode(i).data 
 def getHead(self): return self._head 
 # Mutator method def __setitem__(self, i, item): """Precondition: 0 <= i < len(self) Replace the item at position i. Raise: IndexError""" if i < 0 or i >= len(self): raise IndexError("List out of range.") self._getNode(i).data = item 
 def insert(self, i, item): """Inserts item at the position i.""" # Set the position i between 0 and len(self) if i < 0: i = 0 elif i > len(self): i = len(self) theNode = self._getNode(i) newNode = TwoWayNode(item, theNode.previous, theNode) theNode.previous.next = newNode theNode.previous = newNode self._size += 1 self.incModCount() 
 def pop(self, i=None): """Precondition: 0 <= i < len(self). Remove and return item at position i. if i is None, i is given a default of len(self) - 1" Raise: Index Error.""" if i is None: i = len(self) - 1 if i < 0 or i >= len(self): raise IndexError("List index out of range.") theNode = self._getNode(i) item = theNode.data theNode.previous.next = theNode.next theNode.next.previous = theNode.previous self._size -= 1 self.incModCount() return item 
 def listIterator(self): """Returns a list iterator.""" return LinkedListIterator(self)  | 
|   #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie 
 """ File:arraylistiterator.py """ 
 
 class ArrayListIterator(object): """Represents the list iterator for an array list.""" 
 def __init__(self, backingStore): """Set the initial state of the list iterator.""" self._backingStore = backingStore self._modCount = backingStore.getModCount() self._cursor = 0 self._lastItemPos = -1 self.first() 
 def first(self): """Resets the cursor to the beginning of the backing store.""" self._cursor = 0 self._lastItemPos = -1 
 def last(self): """Moves the cursor to the end of the backing store.""" self._cursor = len(self._backingStore) self._lastItemPos = -1 
 def hasNext(self): """Return True if the iterator has a next item or False otherwise.""" return self._cursor < len(self._backingStore) 
 def next(self): """Precondition: hasNext returns True.The list has not been modified except by this iterator‘s mutator. Returns the current item and advances the cursor to the next item.""" if not self.hasNext(): raise ValueError("No next item in list iterator.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") self._lastItemPos = self._cursor self._cursor += 1 return self._backingStore[self._lastItemPos] 
 def hasPrevious(self): """Return True if the iterator has a previous item or False otherwise""" return self._cursor > 0 
 def previous(self): """Precondition: hasPrevious returns True. The list has not been modified except by this iterator‘s mutator. """ if not self.hasPrevious(): raise ValueError("No previous item in list iterator.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") self._cursor -= 1 self._lastItemPos = self._cursor return self._backingStore[self._lastItemPos] 
 def replace(self, item): """Precondition: the current position is defined. The list has not been modified except by this iterator‘s mutator.""" if self._lastItemPos == -1: raise AttributeError("The current position is undefined.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") self._backingStore[self._lastItemPos] = item self._lastItemPos = -1 
 def insert(self, item): """Precondition: The list has not been modified except by this iterator‘s mutator.""" if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") if self._lastItemPos == -1: # Cursor not defined, so add item to end of list. self._backingStore.add(item) else: self._backingStore.insert(self._lastItemPos, item) # If the item insert was obtained via next, move cursor forward if self._lastItemPos < self._cursor: self._cursor += 1 self._lastItemPos = -1 self._modCount += 1 
 def remove(self): """Precondition: the current position is defined. The list has not been modified except by this iterator‘s mutator.""" if self._lastItemPos == -1: raise AttributeError("The current position is undefined.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("List has been modified illegally.") self._backingStore.pop(self._lastItemPos) # If the item removed was obtained via next, move cursor back if self._lastItemPos < self._cursor: self._cursor -= 1 self._modCount += 1 self._lastItemPos = -1  | 
|   #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie 
 """ File:linkedlistiterator.py """ 
 from node import TwoWayNode 
 
 class LinkedListIterator(object): """Represents the list iterator for an linked list.""" 
 def __init__(self, backingStore): """Set the initial state of the list iterator.""" self._backingStore = backingStore self._modCount = backingStore.getModCount() self._head = backingStore.getHead() self._cursor = self._head self._lastItemPos = None self.first() 
 def first(self): """Resets the cursor to the beginning of the backing store.""" self._cursor = self._head.next self._lastItemPos = None 
 def last(self): """Moves the cursor to the end of the backing store.""" self._cursor = self._head.previous self._lastItemPos = None 
 def hasNext(self): """Return True if the iterator has a next item or False otherwise.""" return self._cursor.next != self._head 
 def next(self): """Precondition: hasNext returns True.The list has not been modified except by this iterator‘s mutator. Returns the current item and advances the cursor to the next item.""" if not self.hasNext(): raise ValueError("No next item in list iterator.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") self._lastItemPos = self._cursor self._cursor = self._cursor.next return self._lastItemPos.data 
 def hasPrevious(self): """Return True if the iterator has a previous item or False otherwise""" return self._cursor.previous != self._head 
 def previous(self): """Precondition: hasPrevious returns True. The list has not been modified except by this iterator‘s mutator. """ if not self.hasPrevious(): raise ValueError("No previous item in list iterator.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") self._lastItemPos = self._cursor self._cursor = self._cursor.previous return self._lastItemPos.data 
 def replace(self, item): """Precondition: the current position is defined. The list has not been modified except by this iterator‘s mutator.""" if self._lastItemPos is None: raise AttributeError("The current position is undefined.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") self._lastItemPos.data = item self._lastItemPos = None 
 def insert(self, item): """Precondition: The list has not been modified except by this iterator‘s mutator.""" if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") if self._lastItemPos is None: # Cursor not defined, so add item to end of list. self._backingStore.add(item) else: newNode = TwoWayNode(item, self._lastItemPos.previous, self._lastItemPos) self._lastItemPos.previous.next = newNode self._lastItemPos.previous = newNode self._backingStore.incModCount() self._lastItemPos = None self._modCount += 1 
 def remove(self): """Precondition: the current position is defined. The list has not been modified except by this iterator‘s mutator.""" if self._lastItemPos is None: raise AttributeError("The current position is undefined.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("List has been modified illegally.") self._lastItemPos.previous.next = self._lastItemPos.next self._lastItemPos.next.previous = self._lastItemPos.previous self._backingStore.incModCount() self._modCount += 1 self._lastItemPos = None  | 
|   #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie 
 """ File: arraysortedlist.py """ 
 from arrays import Array from abstractlist import AbstractList from arraysortedlistiterator import ArraySortedListIterator 
 
 class ArraySortedList(AbstractList): """An array-based sorted list implementation.""" 
 # Class variable DEFAULT_CAPACITY = 10 
 def __init__(self, sourceCollection=None): """Sets the initial state of self, which includes the contents of sourceCollection, if it‘s present.""" self._items = Array(ArraySortedList.DEFAULT_CAPACITY) AbstractList.__init__(self, sourceCollection) 
 # Accessor method def __iter__(self): """Support iteration over a view of self.""" cursor = 0 while cursor < len(self): yield self._items[cursor] cursor += 1 
 def __getitem__(self, i): """Precondition: 0<= i < len(self) Return the item at position i. Raises: IndexError""" 
 if i < 0 or i >= len(self): raise IndexError("List out of range.") return self._items[i] 
 def __contains__(self, item): position = self._binarySearch(item) if self._items[position] == item: return True else: return False 
 def _binarySearch(self, item): """Search item in the array sorted list.""" left = 0 right = len(self) - 1 mid = len(self) while left <= right: mid = (left + right) // 2 if self._items[mid] == item: break if self._items[mid] > item: right = mid - 1 else: left = mid + 1 return mid 
 def index(self, item): """Precondition: the item is in the list. Return the position of the item. Raise: ValueError if item isn‘t in the list""" position = self._binarySearch(item) if self._items[position] != item: raise ValueError(str(item) + " isn‘t in the list.") # find the first position if there is multiply items for i in range(position - 1, -1, -1): if self._items[i] != item: return i + 1 # return the first place return 0 
 # Mutator method def pop(self, i=None): """Precondition: 0 <= i < len(self). Remove and return item at position i. if i is None, i is given a default of len(self) - 1" Raise: Index Error.""" if i is None: i = len(self) - 1 if i < 0 or i >= len(self): raise IndexError("List index out of range.") item = self._items[i] for index in range(i, len(self) - 1): self._items[index] = self._items[index + 1] self._items[len(self) - 1] = None self._size -= 1 self.incModCount() # Resize array in necessary self._shrinkArray() return item 
 def add(self, item): """Add the item to the proper position of the list.""" # Resize the array if necessary. self._growArray() # Find the position by binary search position = self._binarySearch(item) flag = True if self._items[position] is not None and item > self._items[position]: for i in range(position + 1, len(self)): if item <= self._items[i]: position = i flag = False break if flag: position = len(self) else: for i in range(position - 1, -1, -1): if item >= self._items[i]: position = i + 1 flag = False break if flag: position = 0 # Insert item at the proper position. if position < len(self): for index in range(len(self), position, -1): self._items[index] = self._items[index - 1] self._items[position] = item self._size += 1 self.incModCount() 
 def listIterator(self): """Returns a list iterator.""" return ArraySortedListIterator(self) 
 def _growArray(self): """Grow the capacity of the array if necessary """ physicalSize = len(self._items) if len(self) >= physicalSize: temp = Array(physicalSize * 2) index = 0 for item in self: temp[index] = item index += 1 self._items = temp 
 def _shrinkArray(self): """Shrink the capacity of the array if necessary. """ physicalSize = len(self._items) if len(self) <= physicalSize // 4 and physicalSize >= 2 * ArraySortedList.DEFAULT_CAPACITY: temp = Array(physicalSize // 2) index = 0 for item in self: temp[index] = item index += 1 self._items = temp  | 
|   #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie 
 """ File: ArrayList.py """ 
 from abstractlist import AbstractList from arraysortedlist import ArraySortedList from arraylistiterator import ArrayListIterator 
 
 class ArrayList(ArraySortedList): """An array-based list implementation.""" 
 def __init__(self, sourceCollection=None): """Sets the initial state of self, which includes the contents of sourceCollection, if it‘s present.""" ArraySortedList.__init__(self, sourceCollection) 
 # Accessor method def index(self, item): """Precondition: the item is in the list. Return the position of the item. Raise: ValueError if item isn‘t in the list""" AbstractList.index(self, item) 
 def __contains__(self, item): for i in self: if i == item: return True return False 
 # Mutator method def __setitem__(self, i, item): """Precondition: 0 <= i < len(self) Replace the item at position i. Raise: IndexError""" if i < 0 or i >= len(self): raise IndexError("List out of range.") self._items[i] = item 
 def insert(self, i, item): """Inserts item at the position i.""" # Resize the array if necessary self._growArray() # Set the position i between 0 and len(self) if i < 0: i = 0 elif i > len(self): i = len(self) if i < len(self): for index in range(len(self), i, -1): self._items[index] = self._items[index - 1] self._items[i] = item self._size += 1 self.incModCount() 
 def add(self, item): """Add the item to the end of the list.""" AbstractList.add(self, item) 
 def listIterator(self): """Returns a list iterator.""" return ArrayListIterator(self)  | 
|   #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie 
 """ File:arraysortedlistiterator.py """ 
 
 class ArraySortedListIterator(object): """Represents the list iterator for a sorted array list.""" 
 def __init__(self, backingStore): """Set the initial state of the list iterator.""" self._backingStore = backingStore self._modCount = backingStore.getModCount() self._cursor = 0 self._lastItemPos = -1 self.first() 
 def first(self): """Resets the cursor to the beginning of the backing store.""" self._cursor = 0 self._lastItemPos = -1 
 def last(self): """Moves the cursor to the end of the backing store.""" self._cursor = len(self._backingStore) self._lastItemPos = -1 
 def hasNext(self): """Return True if the iterator has a next item or False otherwise.""" return self._cursor < len(self._backingStore) 
 def next(self): """Precondition: hasNext returns True.The list has not been modified except by this iterator‘s mutator. Returns the current item and advances the cursor to the next item.""" if not self.hasNext(): raise ValueError("No next item in list iterator.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") self._lastItemPos = self._cursor self._cursor += 1 return self._backingStore[self._lastItemPos] 
 def hasPrevious(self): """Return True if the iterator has a previous item or False otherwise""" return self._cursor > 0 
 def previous(self): """Precondition: hasPrevious returns True. The list has not been modified except by this iterator‘s mutator. """ if not self.hasPrevious(): raise ValueError("No previous item in list iterator.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") self._cursor -= 1 self._lastItemPos = self._cursor return self._backingStore[self._lastItemPos] 
 def remove(self): """Precondition: the current position is defined. The list has not been modified except by this iterator‘s mutator.""" if self._lastItemPos == -1: raise AttributeError("The current position is undefined.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("List has been modified illegally.") self._backingStore.pop(self._lastItemPos) # If the item removed was obtained via next, move cursor back if self._lastItemPos < self._cursor: self._cursor -= 1 self._modCount += 1 self._lastItemPos = -1  | 
|   #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Lijunjie 
 """ File:arraylistiterator.py """ 
 from arraysortedlistiterator import ArraySortedListIterator 
 
 class ArrayListIterator(ArraySortedListIterator): """Represents the list iterator for an array list.""" 
 def __init__(self, backingStore): """Set the initial state of the list iterator.""" ArraySortedListIterator.__init__(self, backingStore) 
 def replace(self, item): """Precondition: the current position is defined. The list has not been modified except by this iterator‘s mutator.""" if self._lastItemPos == -1: raise AttributeError("The current position is undefined.") if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") self._backingStore[self._lastItemPos] = item self._lastItemPos = -1 
 def insert(self, item): """Precondition: The list has not been modified except by this iterator‘s mutator.""" if self._modCount != self._backingStore.getModCount(): raise AttributeError("Illegal modification of backing store.") if self._lastItemPos == -1: # Cursor not defined, so add item to end of list. self._backingStore.add(item) else: self._backingStore.insert(self._lastItemPos, item) # If the item insert was obtained via next, move cursor forward if self._lastItemPos < self._cursor: self._cursor += 1 self._lastItemPos = -1 self._modCount += 1  | 
标签:包含 play 数据类型 有序 定位 链表实现 ons pyhon get
原文地址:https://www.cnblogs.com/lijunjie9502/p/9938654.html