From 537c29935ccf1d750863894ec49c983f32e97b86 Mon Sep 17 00:00:00 2001 From: Orest Ivasiv Date: Fri, 15 Dec 2023 21:40:19 +0100 Subject: [PATCH] upd leetcode.md --- docs/wiki/misc/leetcode.md | 94 ++++++++++++++++++++------------------ 1 file changed, 50 insertions(+), 44 deletions(-) diff --git a/docs/wiki/misc/leetcode.md b/docs/wiki/misc/leetcode.md index 06c22e0..ac221b7 100644 --- a/docs/wiki/misc/leetcode.md +++ b/docs/wiki/misc/leetcode.md @@ -106,47 +106,53 @@ Variable | Meaning ### Initialize List -We can create a list through `*` operator if the item in the list expression is an immutable object. - -```python ->>> a = [None] * 3 ->>> a -[None, None, None] ->>> a[0] = "foo" ->>> a -['foo', None, None] -``` - -However, if the item in the list expression is a **mutable** object, the `*` operator will copy the reference of the item `N` times (i.e. *all objects in the list point to the same address*). In order to avoid this pitfall, we should use a list comprehension to initialize a list: - - -```python ->>> a = [[]] * 3 ->>> b = [[] for _ in range(3)] ->>> a[0].append("Hello") ->>> a -[['Hello'], ['Hello'], ['Hello']] ->>> b[0].append("Python") ->>> b -[['Python'], [], []] -``` - -### Initialize Matrix (List of Lists) - -```python ->>> rows = 2 ->>> cols = 3 ->>> [[0] * cols for _ in range(rows)] -[[0, 0, 0], [0, 0, 0]] -``` - -Again, DON'T do this - -```python ->>> a = [[0] * 3] * 3 ->>> a -[[0, 0, 0], [0, 0, 0], [0, 0, 0]] ->>> a[1][1] = 2 ->>> a -[[0, 2, 0], [0, 2, 0], [0, 2, 0]] -``` \ No newline at end of file +Initialize | How +-|- +List | `[None] * size` +Matrix | `[[0] * cols for _ in range(rows)]` + +??? warning + + We can create a list through `*` operator if the item in the list expression is an immutable object. + + ```python + >>> a = [None] * 3 + >>> a + [None, None, None] + >>> a[0] = "foo" + >>> a + ['foo', None, None] + ``` + + However, if the item in the list expression is a **mutable** object, the `*` operator will copy the reference of the item `N` times (i.e. *all objects in the list point to the same address*). In order to avoid this pitfall, we should use a list comprehension to initialize a list: + + ```python + >>> a = [[]] * 3 + >>> b = [[] for _ in range(3)] + >>> a[0].append("Hello") + >>> a + [['Hello'], ['Hello'], ['Hello']] + >>> b[0].append("Python") + >>> b + [['Python'], [], []] + ``` + + **Initialize Matrix (List of Lists)** + + ```python + >>> rows = 2 + >>> cols = 3 + >>> [[0] * cols for _ in range(rows)] + [[0, 0, 0], [0, 0, 0]] + ``` + + Again, DON'T do this + + ```python + >>> a = [[0] * 3] * 3 + >>> a + [[0, 0, 0], [0, 0, 0], [0, 0, 0]] + >>> a[1][1] = 2 + >>> a + [[0, 2, 0], [0, 2, 0], [0, 2, 0]] + ``` \ No newline at end of file