class Grid(object): """Represents a two-dimensional array.""" def __init__(self, rows, columns, fillValue=None): self._data = Array(rows) for row in range(rows): self._data[row] = Array(columns, fillValue) def getHeight(self): """Returns the number of rows.""" return self._data.size() def getWidth(self): """Returns the number of columns.""" return len(self._data[0]) def __getitem__(self, index): """Supports two-dimensional indexing with [row][column].""" return self._data[index] def __str__(self): """Returns a string representation of the grid.""" result = "" for row in range(self.getHeight()): for col in range(self.getWidth()): result += str(self._data[row][col]) + " " result += "\n" return result
def add(self, item): if self._size == len(self._items): temp = Array(self._size * 2) for i in range(self._size): temp[i] = self._items[i] self._items = temp # if self.isEmpty() or item >= self._items[len(self) - 1]: ArrayBag.add(self, item) else: targetIndex = 0 while item > self._items[targetIndex]: targetIndex += 1 for i in range(len(self), targetIndex, -1): self._items[i] = self._items[i - 1] self._items[targetIndex] = item self._size += 1
def pop(self): """Removes and returns the item at the top of the stack. Precondition: the stack is not empty. Raises: KeyError if stack is empty. Postcondition: the top item is removed from the stack.""" if self.size == 0: raise KeyError("No items to pop.") else: old_item = self.items[len(self) - 1] self.size -= 1 # Resize the array here if necessary if self.size >= 5 and self.size <= (len(self.items) // 4): temp = Array(len(self.items) // 2) for rep in range(0, self.size): temp[rep] = self.items[rep] self.items = temp return old_item
def add(self, item): """Adds item to self.""" if len(self._items) == len(self): tempArray = Array(len(self)*2) for i in range(len(self)): tempArray[i] = self._items[i] self._items = tempArray if self.isEmpty() or item >= self._items[len(self) - 1]: self._items[len(self)] = item else: targetPosition = 0 for i in range(len(self)): if item <= self._items[i]: targetPosition = i break for i in range(len(self),targetPosition, -1): self._items[i] = self._items[i-1] self._items[targetPosition] = item self._size += 1
def remove(self, item): """Precondition: item is in self. Raises: KeyError if item in not in self. Postcondition: item is removed from self.""" # Check precondition and raise if necessary if not item in self: raise KeyError(str(item) + " not in bag") # Shift items to the left of target up by one position for i in range(self._targetIndex, len(self) - 1): self._items[i] = self._items[i + 1] # Decrement logical size self._size -= 1 # Check array memory here and decrease it if necessary if len(self) < len(self._items) // 3 and \ 2 * len(self) >= ArrayBag.DEFAULT_CAPACITY: temp = Array(len(self._items) // 2) for i in range(len(self)): temp[i] = self[i] self._items = temp
def add(self, item): """ If self._rear == self.capacity - 1 and self._size < self._capacity, reset self._rear as 0; if self._rear == self.capacity - 1 and self._size == self._capacity, capacity needs to be expanded. """ if self.isEmpty(): self._front = 0 if self._rear == self._capacity - 1 and self._size < self._capacity: self._rear = 0 self._items[self._rear] = item self._size += 1 else: if self._size == self._capacity: self._capacity += ArrayQueue.default_capacity new_items = Array(self._capacity, source_collection=self._items) # construct a new larger array self._items = new_items self._rear += 1 self._items[self._rear] = item self._size += 1
def pop(self): """Removes and returns the item at the top of the stack. Precondition: the stack is not empty. Raises: KeyError if stack is empty. Postcondition: the top item is removed from the stack.""" if self.isEmpty(): raise KeyError("The stack is empty") oldItem = self._items[len(self) - 1] self._size -= 1 # Resize the array here if necessary if len(self) <= self.DEFAULT_CAPACITY * 0.5: temp = Array(int(ArrayStack.DEFAULT_CAPACITY * 0.75 // 1)) for i in range(len(self)): temp[i] = self._items[i] self._items = temp self.DEFAULT_CAPACITY = int(ArrayStack.DEFAULT_CAPACITY * 0.75) return oldItem
def convert(self): ''' Returns the array of angles on which a camera should turn. :return:Array ''' lst_indexes = [] for el in self.message: lst_indexes.append(self._encode_letter(el)) print("lst", lst_indexes) ar = Array(len(self.message) * 2) index = 0 sum = 0 for el in self.message: ar[index] = self._encode_letter(el)[0] * 22.5 - sum sum += ar[index] ar[index + 1] = 22.5 * self._encode_letter(el)[1] - sum sum += ar[index + 1] index += 2 return ar
def main(): cube = Grid(3, 3) array = [] for i in range(cube.getHeight()): for j in range(cube.getWidth()): cube[i][j] = Array(3) for x in range(cube.getHeight()): for y in range(cube.getWidth()): for z in range(len(cube[x][y])): cube[x][y][z] = str(x) + str(y) + str(z) array.append(cube[x][y][z]) # print(array) head = None for count in range(len(array) - 1, -1, -1): head = Node(array[count], head) while head != None: print(head.data) head = head.next
def pop(self): """Removes and returns the item at the top of the stack. Precondition: the stack is not empty. Raises KeyError if stack is empty. Postcondition: the top item is removed from the stack.""" if self.isEmpty(): raise KeyError("Stack is empty") oldItem = self._items[len(self) - 1] self._items[len(self) - 1] = self._items._fillValue self._size -= 1 # Resize array here if necessary if len(self) <= len(self._items) // 4 and \ len(self._items) >= 2 * ArrayStack.DEFAULT_CAPACITY: # Shrink the size by half but not below default capacity # and remove those garbage cells from the underlying list # self._items.shrink() temp = Array(len(self._items) // 2) # Create a new array for i in range(len(self)): # Copy data from old array temp[i] = self._items[i] # to new array self._items = temp # Reset old array variable to new array return oldItem
def remove(self, item): if not item in self: raise KeyError(str(item) + " is not in bag") targetIndex = 0 for targetItem in self: if targetItem == item: break targetIndex += 1 # shift items to the right of target index by one for i in range(targetIndex, len(self) - 1): self.items[i] = self.items[i + 1] # decrement logical size self.size -= 1 # check array memory / load factor here, decrease size if necessary # performant choice is, if logical size is less than or equal to the 1/4 the length of b and the length of b is greater than 2x the default capacity if self.size <= len(self.items) // 4 and len(self.items) >= ArrayBag.DEFAULT_CAPACITY * 2: temp = Array(len(self.items) // 2) for i in range(self.size): temp[i] = self.items[i] self = temp
def pop(self): """Removes and returns the item at the top of the stack. Precondition: the stack is not empty. Raises: KeyError if stack is empty. Postcondition: the top item is removed from the stack.""" if self.isEmpty(): raise KeyError("The stack is empty") oldItem = self._items[len(self) - 1] self._size -= 1 self.incModCount() # Resize the array here if necessary if len(self) <= .25 * len(self._items) and \ ArrayStack.DEFAULT_CAPACITY <= len(self._items) // 2: tempArray = Array(len(self._items) // 2) for i in range(len(self)): tempArray[i] = self._items[i] self._items = tempArray return oldItem
def add(self, item): """Adds item to self.""" # Check array memory here and increase it if necessary if len(self._items) == len(self): new_bag = Array(ArraySortedBag.DEFAULT_CAPACITY * 2) for index in range(len(self)): new_bag[index] = self._items[index] self._items = new_bag # Empty or last item, call ArrayBag.add if self.isEmpty() or item >= self._items[len(self) - 1]: ArrayBag.add(self, item) else: # Search for first item >= new item targetIndex = 0 while item > self._items[targetIndex]: targetIndex += 1 # Open a hole for new item for i in range(len(self), targetIndex, -1): self._items[i] = self._items[i - 1] # Insert item and update size self._items[targetIndex] = item self._size += 1
def test_three_arrays(capsys): # Instatiate Array arr = Array(5) # Try inserting an item at index position that does not exist. array_insert(arr, -1, -2) # Try inserting an item at index position that does not exist. array_insert(arr, 1.5, 3) # Try inserting an item at index position that does not exist. array_insert(arr, 3, 100) # Ready array at index 0 assert array_read(arr, 0) == -1 # Read array at index 2 assert array_read(arr, 1) == 1.5 # Read array at index 2 assert array_read(arr, 2) == 3 # Try reading array at an index position that does not exist array_read(arr, 100) # Test the output of the array print function captured = capsys.readouterr() assert captured.out == "Error: Index 100 out of range.\n" # Remove 3 from the array assert array_remove(arr, 3) == 3 # Print the array items array_print(arr) # Test the output of the array print function captured = capsys.readouterr() assert captured.out == "[-1, 1.5]\n" # Try removing an item from the array that does not exist. array_remove(arr, 99) # Test the output of the array print function captured = capsys.readouterr() assert captured.out == "Error: 99 not in list.\n"
def main(): print("Testing the countNumbers function") countNumbers() print("\nTesting the shuffle function") A = Array(10) for i in range(10): A[i] = randint(1,100) print("Original array:", A) shuffle(A) print("After shuffling:", A) print("\nTesting the sumColumn function") matrix = Grid(4,5,0) for r in range(matrix.getHeight()): for c in range(matrix.getWidth()): matrix[r][c] = int(str(r) + str(c)) print("matrix is\n", matrix) print("%6s\t%3s" % ("Column", "Sum")) for column in range(matrix.getWidth()): print("%6d\t%3d" % (column, sumColumn(matrix,column)))
def add(self, item): """Adds item to self.""" # Empty or last item, call ArrayBag.add if self.isEmpty() or item >= self._items[len(self) - 1]: self._items[len(self)] = item self._size += 1 else: # Check array memory here and increase it if necessary if len(self) == len(self._items): temp = Array(2 * len(self)) for i in range(len(self)): temp[i] = self[i] self._items = temp # Search for first item >= new item targetIndex = 0 while item > self._items[targetIndex]: targetIndex += 1 # Open a hole for new item for i in range(len(self), targetIndex, -1): self._items[i] = self._items[i - 1] # Insert item and update size self._items[targetIndex] = item self._size += 1
def main(): """ Main func """ # The constructor is called to create the array. value_list = Array(1) # Fill the array with random floating-point values. for i in range(len(value_list)): value_list[i] = random.random() # Print the values, one per line. for i in range(len(value_list)): print(value_list[i]) for i in value_list: print(i) # get size of list data = [] for i in range(15): a = len(data) b = sys.getsizeof(data) print(" Length: {0:3d}; Size in bytes: {1:4d}".format(a, b)) data.append(None)
def test_one_arrays(capsys): # Instatiate Array arr = Array(1) # Insert item to the array array_insert(arr, "STRING1", 0) # Print the array items array_print(arr) # Test the output of the array print function captured = capsys.readouterr() assert captured.out == "[STRING1]\n" # Pop first item from the array array_pop(arr, 0) # Print the array items array_print(arr) # Test the output of the array print function captured = capsys.readouterr() assert captured.out == "[]\n" # Insert item to the array array_insert(arr, "STRING1", 0) # Append item to the end of the array array_append(arr, "STRING4") # Insert item to the array at index 1 array_insert(arr, "STRING2", 1) # Insert item to the array at index 2 array_insert(arr, "STRING3", 2) # Print the array items array_print(arr) # Test the output of the array print function captured = capsys.readouterr() assert captured.out == "[STRING1, STRING2, STRING3, STRING4]\n"
def add(self, item): # 判断是否需要扩容 if len(self) == len(self._items): temp = Array(2 * len(self)) for i in range(len(self)): temp[i] = self._items[i] self._items = temp if self.isEmpty() or item > self._items[len(self) - 1]: ArrayBag.add(self, item) else: left = 0 right = len(self) - 1 # 找到第一个大于等于item的项 while left < right: mid = left + (right - left) // 2 if self._items[mid] < item: left = mid + 1 else: right = mid # left是第一个大于item的index for i in range(len(self), left, -1): self._items[i] = self._items[i - 1] self._items[left] = item self._size += 1
def __init__(self, sourceCollection=None): """Sets the initial state of self, which includes the contents of source_collection, if it's present.""" self._front = self._rear = -1 self._items = Array(ArrayQueue.DEFAULT_CAPACITY) AbstractCollection.__init__(self, sourceCollection)
def clear(self): """Makes self become empty.""" self._size = 0 self._items = Array(ArraySortedBag.DEFAULT_CAPACITY) self._modCount += 1
def clear(self): """Makes self become empty.""" # Exercise self._items = Array(ArrayBag.DEFAULT_CAPACITY) self._size = 0 #will print {None} if don't add this
from arrays import Array algo = Array(10) #EJEMPLO ITERADOR, GET,CLEAR print(algo.get_item(6363)) algo.set_item(555, 3) print(algo.get_item(3)) print(f"El arreglo tiene {algo.get_length()} elementos") algo.clear(777) print(algo.get_item(3)) print("Prueba del iterador") for x in algo: print(x)
def __init__(self, rows, columns, fillValue=None): self._data = Array(rows) for row in range(rows): self._data[row] = Array(columns, fillValue)
class Salaries(): def __init__(self, file): with open(file, 'r') as txt: rows = txt.readlines() rows = [r.replace(' ', '').strip().split(',') for r in rows] rows.remove(rows[0]) self.__workers = Array(len(rows)) for row in range(self.__workers.get_length()): self.__workers.set_item( (Worker(rows[row][0], rows[row][1], rows[row][2], rows[row][3], rows[row][4], rows[row][5], rows[row][6])), row) def get_final_salary_byID(self, id): for employee in range(self.__workers.get_length()): if (self.__workers.get_item(employee).get_id() == id): name = self.__workers.get_item(employee).get_name() res = self.__workers.get_item(employee).get_final_salary() print(f"Nombre-> {name} , Sueldo final -> {res}") def get_final_salaries(self): for employee in range(self.__workers.get_length()): name = self.__workers.get_item(employee).get_name() res = self.__workers.get_item(employee).get_final_salary() print(f"Nombre-> {name} , Sueldo final -> {res}") def get_empleado_mas_antiguo(self): antiguedad_e = self.__workers.get_item(0).get_antiguedad() empleado = None for employee in range(self.__workers.get_length()): if self.__workers.get_item( employee).get_antiguedad() > antiguedad_e: antiguedad_e = self.__workers.get_item( employee).get_antiguedad() empleado = self.__workers.get_item(employee) return ( f"Empleado más antiguo-> {empleado.to_string()}Años de antiguedad -> {antiguedad_e}" ) def get_empleado_mas_nuevo(self): antiguedad_e = self.__workers.get_item(0).get_antiguedad() empleado = None for employee in range(self.__workers.get_length()): if self.__workers.get_item( employee).get_antiguedad() < antiguedad_e: antiguedad_e = self.__workers.get_item( employee).get_antiguedad() empleado = self.__workers.get_item(employee) return ( f"Empleado más nuevo-> {empleado.to_string()}Años de antiguedad -> {antiguedad_e}" )
from arrays import Array algo = Array(10) print(f"Get item -> {algo.get_item(6363)}") print(f"Set item -> {algo.set_item(555, 2)}") print(f"Get item -> {algo.get_item(2)}") print(f"El arreglo tiene {algo.get_length()} elementos") algo.clear(123) print(f"Get item -> {algo.get_item(3)}") print("\n----Prueba de iterador----") for x in range(algo.get_length()): print(f"{x} -> {algo.get_item(x)}")
def __init__(self, sourceCollection=None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" self._items = Array(ArrayStack.DEFAULT_CAPACITY) AbstractStack.__init__(self, sourceCollection)
def __init__(self, sourceCollection=None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" self._items = Array(ArrayBag.DEFAULT_CAPACITY) AbstractBag.__init__(self, sourceCollection)
def __init__(self, sourceCollection=None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" self._items = Array(ArrayBag.DEFAULT_CAPACITY) self._targetIndex = -1 AbstractBag.__init__(self, sourceCollection)
def clear(self): """Makes self become empty.""" self._size = 0 self._front = self._rear = -1 self._items = Array(ArrayQueue.DEFAULT_CAPACITY)
def __init__(self): self._items = Array(ArrayStack.DEFAULT_CAPACITY) self._top = -1 self._size = 0
def clear(self): """Makes self become empty.""" self._size = 0 self._items = Array(ArrayStack.DEFAULT_CAPACITY)
def __init__(self, rows, colums, fillValue=None): # 二维数组长和宽 self._data = Array(rows) for row in range(rows): self._data[row] = Array(colums) # 创建二维空数组 即[[], [], []]
class ArrayStack(AbstractStack): """An array-based stack implementation.""" DEFAULT_CAPACITY = 10 # For all array stacks def __init__(self, sourceCollection=None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" self._items = Array(ArrayStack.DEFAULT_CAPACITY) AbstractStack.__init__(self, sourceCollection) # Accessors def __iter__(self): """Supports iteration over a view of self. Visits items from bottom to top of stack.""" cursor = 0 while cursor < len(self): yield self._items[cursor] cursor += 1 def peek(self): """Returns the item at the top of the stack. Precondition: the stack is not empty. Raises KeyError if stack is empty.""" if self.isEmpty(): raise KeyError ("Stack is empty") return self._items[len(self) - 1] # Mutators def clear(self): """Makes self become empty.""" self._size = 0 self._items = Array(ArrayStack.DEFAULT_CAPACITY) def push(self, item): """Inserts item at top of the stack.""" # Resize array here if necessary if self._size == len(self._items): self._items.grow() self._items[len(self)] = item self._size += 1 def pop(self): """Removes and returns the item at the top of the stack. Precondition: the stack is not empty. Raises KeyError if stack is empty. Postcondition: the top item is removed from the stack.""" if self.isEmpty(): raise KeyError ("Stack is empty") oldItem = self._items[len(self)-1] self._items[len(self)-1] = self._items._fillValue self._size -= 1 # Resize array here if necessary if len(self) <= len(self._items) // 4 and \ len(self._items) >= 2 * ArrayStack.DEFAULT_CAPACITY: # Shrink the size by half but not below default capacity # and remove those garbage cells from the underlying list # self._items.shrink() temp = Array(len(self._items) // 2) # Create a new array for i in range(len(self)): # Copy data from old array temp[i] = self._items[i] # to new array self._items = temp # Reset old array variable to new array return oldItem
def __init__(self, rows, columns, fillValue=None): self._data = Array(rows) for row in range(rows): self._data[row] = Array(rows, fillValue)
class ArrayBag(AbstractBag): """An array-based bag implementation.""" # Class variable DEFAULT_CAPACITY = 10 # Constructor def __init__(self, sourceCollection=None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" self._items = Array(ArrayBag.DEFAULT_CAPACITY) self._targetIndex = -1 AbstractBag.__init__(self, sourceCollection) # Accessor methods def __iter__(self): """Supports iteration over a view of self.""" cursor = 0 while cursor < len(self): yield self._items[cursor] cursor += 1 # Mutator methods def clear(self): """Makes self become empty.""" self._size = 0 self._items = Array(ArrayBag.DEFAULT_CAPACITY) def add(self, item): """Adds item to self.""" self._items[len(self)] = item self._size += 1 # Check array memory and increase it if necessary if self._size == len(self._items): self._items.grow() def remove(self, item): """Precondition: item is in self. Raises: KeyError if item is not in self. Postcondition: item is removed from self.""" if not item in self: raise KeyError(str(item) + " not in bag") # Search for index of target item targetIndex = 0 for targetItem in self: if targetItem == item: break targetIndex += 1 # If removing last item, set it to fillValue if targetIndex == len(self) - 1: self._items[targetIndex] = self._items._fillValue else: # Shift items to the left of target up by one position for i in range(targetIndex, len(self) - 1): self._items[i] = self._items[i + 1] self._items[i + 1] = self._items._fillValue # Decrement logical size self._size -= 1 # Check array memory and decrease it if necessary if self._size <= len(self._items) // 4 and len(self._items) > ArrayBag.DEFAULT_CAPACITY: self._items.shrink()
def clear(self): """Makes self become empty.""" self._size = 0 self._items = Array(ArrayBag.DEFAULT_CAPACITY)
class ArrayList(AbstractList): """An array-based list implementation.""" 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(ArrayList.DEFAULT_CAPACITY) AbstractList.__init__(self, sourceCollection) # Accessor Methods def __iter__(self): """Supports 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) Returns the item at position i. Raises: IndexError.""" if i < 0 or i >= len(self): raise IndexError("List index out of range") return self._items[i] # Mutator methods def __setitem__(self, i, item): """Precondition: 0 <= i < len(self) Replaces the item at position i. Raises: IndexError.""" if i < 0 or i >= len(self): raise IndexError("List index out of range") self._items[i] = item def insert(self, i, item): """Inserts the item at position i.""" # Resize the array here if necessary if self._size == len(self._items): self._items.grow() if i < 0: i = 0 elif i > len(self): i = len(self) if i < len(self): for j in range(len(self), i, -1): self._items[j] = self._items[j-1] self._items[i] = item self._size += 1 self.incModCount() def pop(self, i=None): """Precondition: 0 <= i < len(self). Removes and returns the item at position i. If i is None, i is given a default of len(self) - 1. Raises: IndexError.""" if i == None: i = len(self) - 1 if i < 0 or i >= len(self): raise IndexError("List index out of range") item = self._items[i] for j in range(i, len(self) - 1): self._items[j] = self._items[j+1] self._size -= 1 self.incModCount() # Resize the array here if necessary if self._size <= len(self._items) // 4 and len(self._items) > ArrayList.DEFAULT_CAPACITY: self._items.shrink() return item def listIterator(self): """Returns a list iterator.""" return ArrayListIterator(self)