From db7c1358b344f0e92e28971896f174d18de19435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ad=C3=A1n=20Hern=C3=A1ndez=20Baena?= <39740586+HBaena@users.noreply.github.com> Date: Wed, 2 Oct 2019 23:53:22 -0500 Subject: [PATCH] Correcting the snippet format Adding title, tags, explanation. --- snippets/transpose.md | 10 ---------- snippets/transpose_matrix.md | 29 +++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 10 deletions(-) delete mode 100644 snippets/transpose.md create mode 100644 snippets/transpose_matrix.md diff --git a/snippets/transpose.md b/snippets/transpose.md deleted file mode 100644 index 6ec255e5b..000000000 --- a/snippets/transpose.md +++ /dev/null @@ -1,10 +0,0 @@ -## Make a transpose matrix - -```python -def transpose(l): - return list(zip(*l)) - -l = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] -print(transpose(l)) -# Output: [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)] -``` diff --git a/snippets/transpose_matrix.md b/snippets/transpose_matrix.md new file mode 100644 index 000000000..a99aa99d4 --- /dev/null +++ b/snippets/transpose_matrix.md @@ -0,0 +1,29 @@ +--- +title: transpose_matrix +tags: matrix,list,zip,intermediate +--- + +Python `zip()` function takes the iterable elements as input and returns the iterator. +Since zip funtion returns a `zip object`, we can cast it as list wit `list()`. +```py +list(zip([1,2,3],['a','b','c'], [True, False, True])) +# Output: [(1, 'a', True), (2, 'b', False), (3, 'c', True)] +``` + +Using `*list`, we can access to each element of the list +```py +[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] +# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] +*[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] +# Output: [1, 2, 3] [4, 5, 6] [7, 8, 9] [10, 11, 12] +``` + +Combining these two elements we can transpose a matrix. We can access to each row of the matrix using the operator `*` to use them as args of `zip()` function. + +```py +def transpose_matrix(l:list): + return list(zip(*l)) + +print(transpose_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])) +# Output: [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)] +```