uestion as the only structured type i.e. there is no array, list, tuple, etc. (l
ID: 3723673 • Letter: U
Question
uestion as the only structured type i.e. there is no array, list, tuple, etc. (like in Perl). Complete the array class below, that uses a dictionary as its only member variable, so that the sample code hereafter works and yields the desired output. Hint: key index. (5 marks) class array: def-init-( # array constructor # eg: a-array( ) # or a-array( 1,2,3) def _geti tern-C # getter operator [ ] # eg: print( a[2] ) 3/4 def_setitem( # setter operator [ ] # e.g.:a[2]-7 # -' allows appending # after the last element) def str # array printing # eg: print( a )Explanation / Answer
Please find one basic implementation of array by dictioanries in the python3 code below. Error handling can be added to as per the user requirements. Please read the comments carefully as they have the explanation corresponding to the function's working. In case of any further clarification, please comment!
Hope this helps! If this works, please thumbs up!
#################################################################################################
class array:
class_dict={}; # Dictionary member variable
# Initializing an array data structure by a dictionary
def __init__(self,arr_dict):
self.class_dict=arr_dict;
# Extracting the required array element for an index
def __getitem__(self,index):
if index in self.class_dict:
print(self.class_dict[index]);
else :
print("Improper Array Index!!");
# Modifying the required array element for an index
def __setitem__(self,index,value):
self.class_dict[index]=value;
# Displaying the content of array
def __str__(self):
for i in self.class_dict:
print(self.class_dict[i]);
################## Main Program ##################
# Empty dictionary initialization
arr_dict={};
# Reading array inputs
arr_size=int(input("Please enter the size of the array: "));
for i in range(0,arr_size):
arr_dict[i]=int(input('Please input the value: '));
# Initializing array
c=array(arr_dict);
# Using __getitem__ class function by class variable
index_query=int(input("Please enter the index you want the value for: "));
c.__getitem__(index_query);
# Using __setitem__ class function by class variable
index_set=int(input("Please enter the index you want to modify: "));
value_set=int(input("Please enter the new value: "));
c.__setitem__(index_set,value_set);
# Using __str__ class function to display the array
c.__str__();
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.