Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1127b17

Browse files
committed
updates on dynamic array subsection
1 parent 81e0019 commit 1127b17

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""The key is to provide means to grow the Array A that stores all the elements of a list.
2+
When an array is full and we append an element to the list we have to create a new array and copy
3+
the elements of previous array to the new array """
4+
5+
import ctypes # provides low-level arrays
6+
7+
class DynamicArray:
8+
"""A dynamic array class akin to a simplified Python list"""
9+
10+
def __init__(self):
11+
"""Create an empty array"""
12+
self._n=0 #count actual elements
13+
self._capacity=1 #default array capacity
14+
self._A= self._make_array(self.capacity) #low level array creation with capaity one containing nothing.
15+
16+
def __len__(self):
17+
"""Return the number of elements stored in the array"""
18+
return self._n
19+
20+
def __getitem__(self, k): # k is the position in the array where we will get the elements that is in that storage position (k).
21+
if not 0<=k <self._n:
22+
raise IndexError('Invalid Index')
23+
return self._A[k] #retrieve from array
24+
25+
def append(self, obj):
26+
"""Add object to the end of the array"""
27+
if self._n == self._capacity: # if not enough room
28+
self._resize(2*self._capacity) #double the capacity of the array
29+
self._A[self._n]= obj
30+
self._n +=1
31+
32+
def _resize(self, c): #nonpublic utity
33+
"""Resize the internal capacity of the array to c"""
34+
B= self._make_array(c) # creation of new bigger array
35+
36+
for k in range(self._n): #for each existing value
37+
B[k]=self._A[k]
38+
39+
self._A=B #use the bigger Array as the new reference
40+
self._capacity=c
41+
42+
def _make_array(self, c):
43+
"""Retrun new array with capacity c"""
44+
"""ctypes.py_object is a data type in the library that represents a generic python object as a C language object """
45+
return (c* ctypes.py_object) () #Check ctypes documentation. function with no arguments is returned.
46+
47+
list=DynamicArray._make_array(list , 3)
48+
49+
print(list.__len__())
50+
print(list.append(10))
51+
print(list.__getitem__(2))
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import sys
2+
3+
data=[]
4+
n=10
5+
for k in range(n):
6+
a= len(data) # number of elements
7+
b= sys.getsizeof(data) # actual size in bytes
8+
print('Length:{0:3d}; Size in bytes:{1:4d}'.format(a,b))
9+
data.append(None) # increase length by one by appending None (Null) on every kth position of the list data
10+
11+
"""In the array, we can reference the same object 4 times in memory allocations, thus the increase of 32 bytes every 4th element
12+
in the array"""
13+
"""Because a list is a referential structure, the result of getsizeof function for a list instance only includes
14+
the size for representing its primary structure; does not account for memory used by the object itself that are elements of the list.
15+
Meaning each object at ith position in the array has its own memory size along with the memory size of its reference in the array."""
16+
print(data)

PythonDataStructsAndAlgo/Notes.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,13 @@
7373
7474
### Dynamic Arrays and Amortization
7575
> When creating a low-level array in a computer system, the precise size of that array must be explicitly declared in order for the System to properly allocate a consecutive piece of memory for its storage.
76+
77+
> Because the system might dedicate neighboring memory locations to store other data, the capacity of an array cannot trivially be increased by expanding into subsequent cells. In Python tuple and str instances, this constraint is not a problem. The instances of these classes (tuple and str) are immutable (not possible to modify), so the correct size for an underlying array can be fixed when the object is instantiated.
78+
79+
> *Python's list class* presents a more insteresting abstractions. Although a list has a particular length when constructed, the class allows us to add elements to the list, with no apparent limit on the overall capacity of the list. To provide this abstraction, Python relies on *dynamic array* algorithm.
80+
81+
> Because a list is a referential structure, the result of getsizeof function for a list instance only includes the size for representing its primary structure; does not account for memory used by the objects that are elements of the list. Meaning each object at ith position in the array has its own memory size along with the memory size of its reference in the array.
82+
83+
#### Implementing a dynamic array
84+
> The key is to provide means to grow the Array A that stores all the elements of a list. When an array is full and we append an element to the list we have to create a new array and copy the elements of previous array to the new array
85+
>> A common used rule is for the new array to have twice the capacity of the existing array.

0 commit comments

Comments
 (0)