@@ -838,6 +838,22 @@ which incur interpreter overhead.
838838 "Returns the sequence elements n times"
839839 return chain.from_iterable(repeat(tuple(iterable), n))
840840
841+ def sum_of_squares(it):
842+ "Add up the squares of the input values."
843+ # sum_of_squares([10, 20, 30]) -> 1400
844+ return math.sumprod(*tee(it))
845+
846+ def transpose(it):
847+ "Swap the rows and columns of the input."
848+ # transpose([(1, 2, 3), (11, 22, 33)]) --> (1, 11) (2, 22) (3, 33)
849+ return zip(*it, strict=True)
850+
851+ def matmul(m1, m2):
852+ "Multiply two matrices."
853+ # matmul([(7, 5), (3, 5)], [[2, 5], [7, 9]]) --> (49, 80), (41, 60)
854+ n = len(m2[0])
855+ return batched(starmap(math.sumprod, product(m1, transpose(m2))), n)
856+
841857 def convolve(signal, kernel):
842858 # See: https://betterexplained.com/articles/intuitive-convolution/
843859 # convolve(data, [0.25, 0.25, 0.25, 0.25]) --> Moving average (blur)
@@ -1207,6 +1223,17 @@ which incur interpreter overhead.
12071223 >>> list (ncycles(' abc' , 3 ))
12081224 ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
12091225
1226+ >>> sum_of_squares([10 , 20 , 30 ])
1227+ 1400
1228+
1229+ >>> list (transpose([(1 , 2 , 3 ), (11 , 22 , 33 )]))
1230+ [(1, 11), (2, 22), (3, 33)]
1231+
1232+ >>> list (matmul([(7 , 5 ), (3 , 5 )], [[2 , 5 ], [7 , 9 ]]))
1233+ [(49, 80), (41, 60)]
1234+ >>> list (matmul([[2 , 5 ], [7 , 9 ], [3 , 4 ]], [[7 , 11 , 5 , 4 , 9 ], [3 , 5 , 2 , 6 , 3 ]]))
1235+ [(29, 47, 20, 38, 33), (76, 122, 53, 82, 90), (33, 53, 23, 36, 39)]
1236+
12101237 >>> data = [20 , 40 , 24 , 32 , 20 , 28 , 16 ]
12111238 >>> list (convolve(data, [0.25 , 0.25 , 0.25 , 0.25 ]))
12121239 [5.0, 15.0, 21.0, 29.0, 29.0, 26.0, 24.0, 16.0, 11.0, 4.0]
0 commit comments