matrix2.py 1.64 KB
Newer Older
1
2
3
4
# matrix is implemented by list of list
def matrix_maker(ligne, col, val=None):
	m = []
	for i in range(ligne):
Bertrand  NÉRON's avatar
Bertrand NÉRON committed
5
		c = [val] * col
6
7
8
9
10
11
12
13
14
		m.append(c)
	return m

#---- functions that depends on the matrix srtructure 

def matrix_size(m):
	return len(m), len(m[0])

def matrix_get(matrix, i, j):
Bertrand  NÉRON's avatar
Bertrand NÉRON committed
15
	_check_matindex(matrix, i, j)
16
17
18
19
20
21
	return matrix[i][j]

def matrix_set(matrix, i, j, val):
	_check_matindex(matrix,i,j)
	matrix[i][j] = val

Bertrand  NÉRON's avatar
Bertrand NÉRON committed
22
23
24
25
26
27
def to_str(m):
	m_str = []
	for row in m:
		m_str.append('\t'.join([str(cell) for cell in row]))
	m_str = '\n'.join(m_str)
	return m_str
28
29
30
31
32
33



#---- independant regarding matrix structure  
def _check_matindex(matrix,i,j):
	imax, jmax = matrix_size(matrix)
Bertrand  NÉRON's avatar
Bertrand NÉRON committed
34
35
	if (i < 0 or i >= imax) or (j < 0 or j >= jmax):
		raise IndexError("matrix index out of range")
36
37
38
39
40
41
42
43
44


def matrix_get_line(matrix, i):
	_check_matindex(matrix,i,0)
	im, jm = matrix_size(matrix)
	line = []
	for n in range(jm):
		line.append(matrix_get(matrix, i, n))
	return line
Bertrand  NÉRON's avatar
Bertrand NÉRON committed
45
46


47
48
49
50
51
52
53
54
55
56
57
58
59
60
def matrix_set_line(matrix, i, val):
	_check_matindex(matrix,i,0)
	im, jm = matrix_size(matrix)
	for n in range(jm):
		matrix_set(matrix, i, n, val)


def matrix_get_col(matrix, j):
	_check_matindex(matrix,0,j)
	im, jm = matrix_size(matrix)
	col = []
	for n in range(im):
		col.append(matrix_get(matrix, n, j))
	return col
Bertrand  NÉRON's avatar
Bertrand NÉRON committed
61
62


63
64
65
66
67
68
def matrix_set_col(matrix, j, val):
	_check_matindex(matrix,0,j)
	im, jm = matrix_size(matrix)
	for n in range(im):
		matrix_set(matrix, n, j, val)
	
Bertrand  NÉRON's avatar
Bertrand NÉRON committed
69

70
71
72
73
74
75
if __name__ == '__main__':
	m = matrix_maker(5, 3)
	matrix_set(m,0, 0, 1)
	matrix_set(m,0, 2, 2)
	matrix_set(m,4, 0, 12)
	matrix_set(m,4, 2, 15)
Bertrand  NÉRON's avatar
Bertrand NÉRON committed
76
77
78
	print(to_str(m))
	print("get line 0",  matrix_get_line(m, 0))
	print("get col 0", matrix_get_col(m, 0))