-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayList_Structure.py
72 lines (59 loc) · 1.63 KB
/
ArrayList_Structure.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
'''
Implementation of an array list data structure !
'''
class ArrayList:
def __init__(self, arr):
self.arr = arr
self.size = len(arr)
# print array at any given instant
def printArr(self):
print(self.arr)
# return length of input array
def getSize(self):
return self.size
# append to the end of the array
def appendToArray(self, e):
self.arr.append(e)
self.size += 1
# get array value at index i
def getAtIndex(self, i):
try:
return self.arr[i]
except IndexError:
raise Exception("index out of bounds")
# array[i] <- e // print
def setAtIndex(self, i, e):
try:
self.arr[i] = e
except IndexError:
raise Exception("index out of bounds")
# array[i] <- e where the values at indicies [i,size(array)-1] are shifted to the next index
def addAtIndex(self, i, e):
try:
q = self.getSize() - 1
while q > i:
self.arr[q] = self.arr[q-1]
q -= 1
self.arr[i] = e
except IndexError:
raise Exception("index out of bounds")
# array[i] <- NULL where the values at indicies [i,size(array)-1] are shifted to the previous index
def removeAtIndex(self, i):
try:
self.arr[i] = None
q = self.getSize() - 1
while q > i:
self.arr[q-1] = self.arr[q]
q -= 1
except IndexError:
raise Exception("index out of bounds")
if __name__ == '__main__':
arr = ArrayList(['a','b','c','d','e','f','g','h','i','j','k'])
arr.printArr()
print('size of array is ' + str(arr.getSize()))
#print(arr.getAtIndex(1))
arr.setAtIndex(1, 'kamran')
#arr.printArr()
arr.addAtIndex(0, 'abc')
#arr.appendToArray('kam')
arr.printArr()