Exemplo n.º 1
0
 def __init__(self, capacity = 29,
              hashFunction = hash,
              linear = True):
     self._table = Array(capacity, HashTable.EMPTY)
     self._size = 0
     self._hash = hashFunction
     self._homeIndex = -1
     self._actualIndex = -1
     self._linear = linear
     self._probeCount = 0
Exemplo n.º 2
0
 def push(self, item):
     """Inserts item at top of the stack."""
     # Resize array here if necessary
     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
     self._items[len(self)] = item
     self._size += 1
Exemplo n.º 3
0
def countNumbers():
    '''generates and counts numbers 0-9'''
    import random
    counts = Array(10, 0)       
    for i in range(1000):
        num = randint(0, 9)
        counts[num] += 1
    print("%-6s\t%-6s" % ("Number", "Counts"))
    for i in range(len(counts)):
        print("%-6d\t%-6d" % (i, counts[i]))
Exemplo n.º 4
0
    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)
Exemplo n.º 5
0
 def __increasePhysicalSize(self):
     ''' check array memory / load factor here, increase size if necessary'''
     if self.size == len(self.items):
         # create new array and copy data from old array
         # double the size of the array instead of adding one new cell each time the array needs to be resized to ensure better performance
         temp = Array(len(self.items) * 2)
         for i in range(self.size):
             temp[i] = self.items[i]
         # reset old array variable to new array, old arrays memory is left out for the garbage collector
         self.items = temp
         print("increased physical size of array x 2")
Exemplo n.º 6
0
 def push(self, item):
     """Inserts item at top of the stack."""
     # Resize array here if necessary
     if len(self) == len(self._items):
         tempArray = Array(len(self) * 2)
         for i in range(len(self)):
             tempArray[i] = self._items[i]
         self._items = tempArray
     self._items[len(self)] = item
     self._size += 1
     self.incModCount()
Exemplo n.º 7
0
def main():
    arr = Array(7)
    arr.to_string()
    print(f"El arr es de {arr.length()} elementos")
    arr.set_item( 3 , 11 )
    arr.to_string()
    print(f"Elem. en la pos 3 es: { arr.get_item(3) }")
    arr.clearing( 55 )
    arr.to_string()
    arr2d = Array2D(4,4)
    arr2d.to_string()
Exemplo n.º 8
0
 def push(self, item):
     """Inserts item at top of the stack."""
     # Resize array here if necessary
     if len(self._items) == self._size:
         newArray = Array(self._size * 2)
         for i in range(0, self._size):
             newArray[i] = self._items[i]
         self._items = newArray
             
     self._items[len(self)] = item
     self._size += 1
Exemplo n.º 9
0
 def add(self, item):
     """Adds item to self."""
     # Resize array if necessary
     if len(self) == len(self._items):
         tempArray = Array(len(self) * 2)
         for i in range(len(self)):
             tempArray[i] = self._items[i]
         self._items = tempArray
     self._items[len(self)] = item
     self._size += 1
     self.incModCount()
Exemplo n.º 10
0
 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
     self._items[len(self)] = item
     self._size += 1
Exemplo n.º 11
0
def main():
	cube = Grid(3,3)
	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)
				print(cube[x][y][z],end=" ")
			print()
Exemplo n.º 12
0
    def grow(self):
        """Doubles in size"""
        tempArray = Array(len(self) * 2)

        for i in range(self.size()):
            tempArray[i] = self[i]

        for i in range(self.size() + 1, len(tempArray)):
            tempArray[i] = self.defaultFill

        self._items = tempArray
Exemplo n.º 13
0
 def rehash(self):
     """
     This method multiplies the length of array's capacity by two,
     and redistributes the items. Chain lengths will be reduced. 
     """
     items = list(self)
     self._array = Array(len(self._array) * 2)
     self._size = 0
     self._loadedCells = 0
     for item in items:
         self.add(item)
Exemplo n.º 14
0
    def __init__(self, source_collection=None):
        """Set the initial state of self, witch includes the contents of sourceCollection, if it's present"""
        self._capacity = ArrayQueue.default_capacity
        self._items = Array(self._capacity)
        self._size = 0
        self._front = None
        self._rear = None

        if source_collection is not None:
            for item in source_collection:
                self.add(item)
Exemplo n.º 15
0
    def push(self, item):
        """Inserts item at top of the stack."""
        # Resize array here if necessary
        if len(self) == self.DEFAULT_CAPACITY:
            temp = Array(self.DEFAULT_CAPACITY + 1)
            for i in range(len(self)):
                temp[i] = self._items[i]
            self._items = temp
            self.DEFAULT_CAPACITY = int(self.DEFAULT_CAPACITY + 1)

        self._items[len(self)] = item
        self._size += 1
 def __init__(self, source_collection=None):
     self._items = Array(ArrayQueue.DEFAULT_CAPACITY)
     # 默认空队列值为0
     self._front = 0
     self._rear = 0
     AbstractCollection.__init__(self, source_collection)
     # 实例化对象时初始值, 则更改rear的值
     if source_collection != None:
         if type(source_collection) == int:
             self._rear = 0
         else:
             self._rear = len(source_collection) - 1
 def push(self, newItem):
     """Inserts newItem at top of stack."""
     # Resize array if necessary
     if len(self) == len(self._items):
         temp = Array(2 * self._size)
         for i in xrange(len(self)):
             temp[i] = self._items[i]
         self._items = temp
     # newItem goes at logical end of array
     self._top += 1
     self._size += 1
     self._items[self._top] = newItem
 def rehash(self):
     """ 
     Rehash method of Lambert, Kenneth A. (2014) with max load factor
     adjusted from 0.5 to 0.8
     """
     if self.loadFactor() > 0.8:
         items = list(self)
         self._array = Array(len(self._array) * 2)
         self._size = 0
         for item in items:
             self.add(item)
     return self
Exemplo n.º 19
0
 def enqueue(self, newItem):
     """Adds newItem to the rear of queue."""
     # Resize array if necessary
     if len(self) == len(self._items):
         temp = Array(2 * self._size)
         for i in xrange(len(self)):
             temp[i] = self._items[i]
         self._items = temp
     # newItem goes at logical end of array
     self._rear += 1
     self._size += 1
     self._items[self._rear] = newItem
Exemplo n.º 20
0
def test_grow_shrink():
	items = Array(10, 0)

	for count in range(items.size()):
		items[count] = count

	items.shrink(5)
	items.grow(5)

	assert(items.size() == 10)
	assert(items[4] == 4)
	assert(items[9] == 0)
Exemplo n.º 21
0
    def shrink(self):
        """Becomes half the current size, does not become smaller than
             initial capacity."""
        if len(self) // 2 > self.initialCapacity:
            tempArray = Array(len(self) // 2)

            for i in range(self.size()):
                tempArray[i] = self[i]

            self._items = tempArray
        else:
            raise Exception(
                "Cannot shrink the ArrayList below the intialCapacity")
Exemplo n.º 22
0
    def test_array(self):
        '''Testing array class'''
        arr = Array(100)

        self.assertIsInstance(arr, Array)
        self.assertEqual(arr._size, 100)
        self.assertEqual(len(arr), 100)
        
        arr[0] = 'green'
        self.assertEqual(arr[0], 'green')

        arr.clear('red')
        self.assertEqual(arr[0], 'red')
Exemplo n.º 23
0
def test_sort_list_string():
    items = Array(4)
    items[0] = 'bob'
    items[1] = 'joe'
    items[2] = 'jane'
    items[3] = 'isabelle'

    Sort.heapsort(items)

    assert (items[0] == 'bob')
    assert (items[1] == 'isabelle')
    assert (items[2] == 'jane')
    assert (items[3] == 'joe')
Exemplo n.º 24
0
 def pop(self):
     if self.isEmpty():
         raise KeyError('stack is Empty')
     oldItem = self._items[len(self) - 1]
     self._size -= 1
     #
     if self._size < len(self._items) // 4 and \
             len(self._items) >= ArrayStack.DEFAULT_SIZE * 2:
         temp = Array(len(self._items) // 2)
         for i in range(self._size):
             temp[i] = self._items[i]
         self._items = temp
     return oldItem
Exemplo n.º 25
0
 def push(self, item):
     #   check array memory / load factor here, increase size if necessary
     #     increasing size of array
     if self.size == len(self.items):
         # create new array and copy data from old array
         # double the size of the array instead of adding one new cell each time the array needs to be resized to ensure better performance
         temp = Array(len(self.items) * 2)
         for i in range(self.size):
             temp[i] = self.items[i]
         # reset old array variable to new array, old arrays memory is left out for the garbage collector
         self.items = temp
     self.items[len(self)] = item
     self.size += 1
Exemplo n.º 26
0
def test_grow():
	items = Array(10, 132)

	items[5] = 0
	items.grow(10)

	items[15] = 0

	assert(items.size() == 20)
	assert(items[5] == 0)
	assert(items[11] == 132)
	assert(items[15] == 0)
	assert(items[19] == 132)
Exemplo n.º 27
0
 def __init__(self, capacity=29, hashFunction=hash, liner=True):
     """
     :param capacity: hash table 的大小,默认大小为29,可自调节。
     :param hashFunction: 指定hash函数 Python默认为自带的hash函数。
     :param liner: 指定是否使用线性探测器策略,True表示是,False为否。(线性探测器用于解决哈希表中的冲突问题)
     """
     self._table = Array(capacity, HashTable.EMPTY)
     self._size = 0
     self._hash = hashFunction
     self._homeIndex = -1  # 主索引
     self._actualIndex = -1  # 实际索引
     self._liner = liner  # 冲突策略
     self._probeCount = 0  # 探测次数
Exemplo n.º 28
0
 def __init__(self, numAgents, numMinutes, betweenTime, serviceTime):
     """ Parameters supplied by the user."""
     self._arriveProb = 1.0 / betweenTime
     self._serviceTime = serviceTime
     self._numMinutes = numMinutes
      # Simulation components.
     self._passengerQ = Queue()
     self._theAgents = Array(numAgents)
     for i in range(numAgents):
         self._theAgents[i] = TicketAgent(i+1)
      # Computed during the simulation.
     self._totalWaitTime = 0
     self._numPassengers = 0
Exemplo n.º 29
0
    def grow(self):
        """Doubles in size"""
        tempArray = Array(len(self._items) * 2)

        for i in range(self._size):
            tempArray[i] = self._items[i]

 

        self._items = tempArray

            
            
            
Exemplo n.º 30
0
def convert_in():
    """(json) -> Array(SkiWeather)
    Сonvert data from a file to instances of the class."""
    
    f = open('data.json', encoding = 'utf-8')
    all_data = json.load(f)

    ski_list = list(key for key in all_data['resorts'])
    resorts_list = Array(len(ski_list))
    
    for i in range(len(ski_list)):
        resorts_list[i] = SkiWeather(ski_list[i])

    return resorts_list