PR3_Studienleistung_1_Prof_.../s1_a51.py

53 lines
1.5 KiB
Python
Raw Normal View History

2022-11-09 12:31:46 +01:00
class MyMatrix:
# Constructor - parameterized
row = 0
column = 0
matrix = {}
def __init__(self, list):
self.row = len(list)
self.column = len(list[0])
test = len(list[0])
for i in range(len(list)):
if len(list[i]) != test:
raise Exception('Not a matrix')
dictionary = {}
for i in range(self.column):
for j in range(self.row):
if (list[i][j] == 0):
continue
dictionary[i*self.column + j] = list[i][j]
self.matrix = dictionary
def __str__(self):
for i in range((self.row) *(self.column)):
if i % self.column == 0:
print("| ",end="")
if i in self.matrix:
print(f"{self.matrix[i]} ",end="")
else:
print("0 ",end="")
if i % self.column == self.column -1:
print("|\n",end="")
def __getitem__(self, packing):
column2,row1 = packing
if column2 > self.column or row1 > self.row:
raise Exception('Outside of Bounds')
if column2*self.column + row1 in self.matrix:
return self.matrix[column2*self.column + row1]
else:
return 0
m = [[3,0,-2,11],[0,0,9,0],[0,7,0,0],[0,0,0,-3]]
object = MyMatrix(m)
object.__str__()
#Wir haben keine Lösung mitm[0][0]= 3, da __getitem__ nur ein Argument nimmt
x = object[0,0]
print(x)