-
Notifications
You must be signed in to change notification settings - Fork 437
/
Copy pathArrays.py
57 lines (47 loc) · 2.05 KB
/
Arrays.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
# Author: OMKAR PATHAK
class Array(object):
''' sizeOfArray: denotes the total size of the array to be initialized
arrayType: denotes the data type of the array(as all the elements of the array have same data type)
arrayItems: values at each position of array
'''
def __init__(self, sizeOfArray, arrayType = int):
self.sizeOfArray = len(list(map(arrayType, range(sizeOfArray))))
self.arrayItems =[arrayType(0)] * sizeOfArray # initialize array with zeroes
self.arrayType = arrayType
def __str__(self):
return ' '.join([str(i) for i in self.arrayItems])
def __len__(self):
return len(self.arrayItems)
# magic methods to enable indexing
def __setitem__(self, index, data):
self.arrayItems[index] = data
def __getitem__(self, index):
return self.arrayItems[index]
# function for search
def search(self, keyToSearch):
for i in range(self.sizeOfArray):
if (self.arrayItems[i] == keyToSearch): # brute-forcing
return i # index at which element/ key was found
return -1 # if key not found, return -1
# function for inserting an element
def insert(self, keyToInsert, position):
if(self.sizeOfArray > position):
for i in range(self.sizeOfArray - 2, position - 1, -1):
self.arrayItems[i + 1] = self.arrayItems[i]
self.arrayItems[position] = keyToInsert
else:
print('Array size is:', self.sizeOfArray)
# function to delete an element
def delete(self, keyToDelete, position):
if(self.sizeOfArray > position):
for i in range(position, self.sizeOfArray - 1):
self.arrayItems[i] = self.arrayItems[i + 1]
self.arrayItems[i + 1] = self.arrayType(0)
else:
print('Array size is:', self.sizeOfArray)
if __name__ == '__main__':
a = Array(10, int)
a.insert(2, 2)
a.insert(3, 1)
a.insert(4,7)
print(len(a))