Can someone please explain whats going on in this code Can comments be added please? class twoDarray(list): def __init__(self, array): try: if(not isinstance(array[0],list)): raise TypeError x = len(array[0]) for i in array: if len(i)!=x: raise KeyError except TypeError: print("error Not a 2d array.") return except KeyError: print("error Lists are not of equal size.") return self.array = array def __str__(self): return '[' + "\n ".join([str(arr) for arr in self.array]) + ']' def shape(self): return (len(self.array), len(self.array[0]))
Can someone please explain whats going on in this code
Can comments be added please?
class twoDarray(list):
def __init__(self, array):
try:
if(not isinstance(array[0],list)):
raise TypeError
x = len(array[0])
for i in array:
if len(i)!=x:
raise KeyError
except TypeError:
print("error Not a 2d array.")
return
except KeyError:
print("error Lists are not of equal size.")
return
self.array = array
def __str__(self):
return '[' + "\n ".join([str(arr) for arr in self.array]) + ']'
def shape(self):
return (len(self.array), len(self.array[0]))
The given code mimics the functionality of numpy array by creating a separate class named twoDarray.
The given code checks the validity of two dimensional matrix .
A two dimensional matrix is valid,
- if it is a list of lists
- If the length of all lists in the list is same
If the two dimensional matrix is valid, it prints the two dimensional matrix else prints appropriate error message.
The shape() method prints the dimensions of two dimensional matrix.
Trending now
This is a popular solution!
Step by step
Solved in 4 steps with 2 images