-
Notifications
You must be signed in to change notification settings - Fork 3
/
Matrix_Addition.py
74 lines (63 loc) · 1.51 KB
/
Matrix_Addition.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# Kata link:
# https://www.codewars.com/kata/526233aefd4764272800036f/
# -------------------------------------
# Instructions:
'''
Write a function that accepts two square matrices (N x N two dimensional
arrays), and return the sum of the two. Both matrices being passed into
the function will be of size N x N (square), containing only integers.
How to sum two matrices:
Take each cell [n][m] from the first matrix, and add it with the same
[n][m] cell from the second matrix. This will be cell [n][m] of the
solution matrix.
Visualization:
|1 2 3| |2 2 1| |1+2 2+2 3+1| |3 4 4|
|3 2 1| + |3 2 3| = |3+3 2+2 1+3| = |6 4 4|
|1 1 1| |1 1 3| |1+1 1+1 1+3| |2 2 4|
Example
matrixAddition(
[ [1, 2, 3],
[3, 2, 1],
[1, 1, 1] ],
// +
[ [2, 2, 1],
[3, 2, 3],
[1, 1, 3] ] )
// returns:
[ [3, 4, 4],
[6, 4, 4],
[2, 2, 4] ]
'''
# -------------------------------------
# Solution
def matrix_addition(a, b):
return [[x + y for x, y in zip(first, second)] for first, second in zip(a,b)]
# -------------------------------------
print('Basic Tests:')
print(matrix_addition(
[ [1, 2],
[1, 2] ],
# +
[ [2, 3],
[2, 3] ] )
==
[ [3, 5],
[3, 5] ] )
print(matrix_addition(
[ [1] ],
# +
[ [2] ] )
==
[ [3] ] )
print(matrix_addition(
[ [1, 2, 3],
[3, 2, 1],
[1, 1, 1] ],
# +
[ [2, 2, 1],
[3, 2, 3],
[1, 1, 3] ] )
==
[ [3, 4, 4],
[6, 4, 4],
[2, 2, 4] ] )