@@ -1036,10 +1036,15 @@ The following recipes have a more mathematical flavor:
1036
1036
# sum_of_squares([10, 20, 30]) -> 1400
1037
1037
return math.sumprod(*tee(it))
1038
1038
1039
- def transpose(it):
1040
- "Swap the rows and columns of the input."
1039
+ def reshape(matrix, cols):
1040
+ "Reshape a 2-D matrix to have a given number of columns."
1041
+ # reshape([(0, 1), (2, 3), (4, 5)], 3) --> (0, 1, 2), (3, 4, 5)
1042
+ return batched(chain.from_iterable(matrix), cols)
1043
+
1044
+ def transpose(matrix):
1045
+ "Swap the rows and columns of a 2-D matrix."
1041
1046
# transpose([(1, 2, 3), (11, 22, 33)]) --> (1, 11) (2, 22) (3, 33)
1042
- return zip(*it , strict=True)
1047
+ return zip(*matrix , strict=True)
1043
1048
1044
1049
def matmul(m1, m2):
1045
1050
"Multiply two matrices."
@@ -1254,6 +1259,22 @@ The following recipes have a more mathematical flavor:
1254
1259
>>> sum_of_squares([10 , 20 , 30 ])
1255
1260
1400
1256
1261
1262
+ >>> list (reshape([(0 , 1 ), (2 , 3 ), (4 , 5 )], 3 ))
1263
+ [(0, 1, 2), (3, 4, 5)]
1264
+ >>> M = [(0 , 1 , 2 , 3 ), (4 , 5 , 6 , 7 ), (8 , 9 , 10 , 11 )]
1265
+ >>> list (reshape(M, 1 ))
1266
+ [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,), (10,), (11,)]
1267
+ >>> list (reshape(M, 2 ))
1268
+ [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]
1269
+ >>> list (reshape(M, 3 ))
1270
+ [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
1271
+ >>> list (reshape(M, 4 ))
1272
+ [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
1273
+ >>> list (reshape(M, 6 ))
1274
+ [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11)]
1275
+ >>> list (reshape(M, 12 ))
1276
+ [(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)]
1277
+
1257
1278
>>> list (transpose([(1 , 2 , 3 ), (11 , 22 , 33 )]))
1258
1279
[(1, 11), (2, 22), (3, 33)]
1259
1280
0 commit comments