# Python code cheatsheet

**Random**

`import random`\
`random_idx = random.randint(low, high)`

Default Min and Max

* Use `float('inf')` for positive infinity.
* Use `float('-inf')` for negative infinity.xfcha

dict

```python
nodeInfo = dict()
nodeInfo[ng] = nodeInfo.get(ng, 0) + 1 #有则返回vaL 无则返回0 这样可以无需初始化

```

**如何统计字典中某个值的出现次数？**

用 `list(dict.values()).count(x)`

#### 🔍 `parent.get(key)` vs `parent[key]`

* `parent[key]`：如果字典中没有这个 key，会直接抛出 **`KeyError`**
* `parent.get(key)`：如果 key 不存在，不会报错，而是返回 **`None`**

deque

一般 qfs里使用， 用popleft取代list.pop(0), time complexity: o(n) => o(1)

```
q = deque()
cur = q.popleft()

```

数组slicing

reverse ： s\[::-1] start:stop:step

```
s = "hello"
reversed_s = s[::-1]
print(reversed_s)  # Output: "olleh"
```

```
presums[-1] will return last element of the list
```

二维数组

```
dp = [[0]*(m+1) for _ in range(n+1)]

```

```
n//2 vs n/2
n//2 floor, return int
n/2 true division, return float

```

Ord(): return unicode code point of a charactor

```
print(ord('a'))  # Output: 97
```

sort 自定义函数

```
pairs.sort(key = lambda x: (x[1],x[0]))#记得要加括号！！！！
```

\
\*list will unpack the list

```
workers = [1, 2, 3, 4]
# Using *workers in a print statement
print(*workers)    # Output: 1 2 3 4
```

default: **Functions**: `max()` and `min()` support the `default` parameter.

<pre><code><strong>min/max([], default=0)  # Returns 0
</strong>
</code></pre>

遍历dictionary:

````
```python
for k,v in d.items():
    v.reserse() #v is a list
```
````

number char coversion

`char.isdigit()`&#x20;

`char.isalpha()`

#### &#x20;**Convert a Character to its ASCII/Unicode Number**

`char = 'A' number = ord(char) print(number) # Output: 65`

#### **Convert a Numeric Character to its Integer Value**

`char = '7' number = int(char) print(number) # Output: 7`

**Counter**

&#x20;`Counter(list)`  returnr dict.

&#x20;**most\_common**(k) returns a list of `(element, count)` tuples sorted by counts.

```

return [i for i,_ in collections.Counter(nums).most_common(k)]

```

**Sort**

Define a lambda function to sort various data structures like lists, dictionaries, and tuples.

**In-place vs. Copy**:

* `sorted()` returns a new sorted list.
* `.sort()` sorts the list in place and returns `None`.

#### Sorting a List

```
# Example list of tuples
data = [(1, 3), (4, 1), (5, 2)]

# Sorting the list based on the second element of each tuple
sorted_data = sorted(data, key=lambda x: x[1])

# Output: [(4, 1), (5, 2), (1, 3)]
print(sorted_data)

```

#### Sorting a Dictionary by Value

```
# Example dictionary
data = {'a': 3, 'b': 1, 'c': 2}

# Sorting the dictionary by its values
sorted_data = sorted(data.items(), key=lambda x: x[1])

# Output: [('b', 1), ('c', 2), ('a', 3)]
print(sorted_data)

```

#### Sorting a List of Dictionaries

```
# Example list of dictionaries
data = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 22}, {'name': 'Doe', 'age': 30}]

# Sorting by the 'age' key
sorted_data = sorted(data, key=lambda x: x['age'])

# Output: [{'name': 'Jane', 'age': 22}, {'name': 'John', 'age': 25}, {'name': 'Doe', 'age': 30}]
print(sorted_data)

```

deque

整个list 加入deque, extend()

```
d.extend(lst)
```

use cache in DP

```
from functools import lru_cache  # Import lru_cache
@lru_cache(None)

```

filter

参数是一个函数和iterator，函数作用在每个iterator上&#x20;

<pre><code><strong>#滤掉所有非(),因为count返回返回1或0
</strong><strong>s = "a(b)c)d"
</strong>result = ''.join(filter('()'.count, s))
print(result)  # Output: "()()"

</code></pre>

<mark style="color:red;">**Concise code**</mark>

**1️⃣ Multiple Appends in One Line**

Instead of:

```python
pythonCopyEditqueue.append(item1)
queue.append(item2)
```

Use:

```python
pythonCopyEditqueue.extend([item1, item2])
```

Or:

```python
pythonCopyEditqueue += item1, item2  # No need for extra brackets!
```

***

**2️⃣ Inline If-Else (`or` Trick)**

Instead of:

```python
pythonCopyEditif name:
    greeting = name
else:
    greeting = "Guest"
```

Use:

```python
pythonCopyEditgreeting = name or "Guest"
```

* If `name` is `None` or `""`, it defaults to `"Guest"`.

***

**3️⃣ Swapping Variables Without Temp**

Instead of:

```python
pythonCopyEdittemp = a
a = b
b = temp
```

Use:

```python
pythonCopyEdita, b = b, a
```

***

**4️⃣ List Comprehension Instead of Loops**

Instead of:

```python
pythonCopyEditsquares = []
for i in range(10):
    squares.append(i * i)
```

Use:

```python
pythonCopyEditsquares = [i * i for i in range(10)]
```

***

**5️⃣ Using `defaultdict` to Avoid Key Errors**

Instead of:

```python
pythonCopyEditword_count = {}
for word in words:
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1
```

Use:

```python
pythonCopyEditfrom collections import defaultdict
word_count = defaultdict(int)
for word in words:
    word_count[word] += 1
```

***

**6️⃣ Merging Two Dictionaries**

Instead of:

```python
pythonCopyEditdict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1.copy()
merged.update(dict2)
```

Use (Python 3.9+):

```python
pythonCopyEditmerged = dict1 | dict2
```

***

**7️⃣ Unpacking Iterables**

Instead of:

```python
pythonCopyEdita = my_list[0]
b = my_list[1]
c = my_list[2:]
```

Use:

```python
pythonCopyEdita, b, *c = my_list
```

***

**BIT**

| `bin(mask)` | 转二进制字符串（带 `0b` 前缀） | `'0b101'` |
| ----------- | ------------------ | --------- |

| `mask.bit_count()` | 直接统计 `1` 的个数（Python 3.10+） | `2`（若 `mask = 0b1010`） |
| ------------------ | -------------------------- | ---------------------- |

#### **`pos = available & -available` 的作用：取最低位的 `1`**

**核心原理**

* **`available`**：一个二进制数，表示当前可选的位置（`1` 表示可选，`0` 表示不可选）。
  * 例如 `available = 0b1010` 表示第 2 列和第 4 列可选（从右往左数，最低位是第 1 列）。
* **`-available`**：计算机中负数以补码表示，`-x = ~x + 1`。
  * 例如 `available = 0b1010`，则 `-available = ~0b1010 + 1 = 0b0101 + 1 = 0b0110`。
* **`available & -available`**：
  * 保留 `available` 最低位的 `1`，其余位全置 `0`。
  * 例如 `0b1010 & 0b0110 = 0b0010`（保留了最低位的 `1`）。

**Count**

| **数据类型**    | **是否支持 `.count()`** | **统计对象** | **示例**                      |
| ----------- | ------------------- | -------- | --------------------------- |
| 字符串（`str`）  | ✅                   | 子字符串     | `"hello".count("l")`        |
| 列表（`list`）  | ✅                   | 元素       | `[1, 2, 2].count(2)`        |
| 元组（`tuple`） | ✅                   | 元素       | `(1, 2, 2).count(2)`        |
| 字节（`bytes`） | ✅                   | 子字节序列    | `b"hello".count(b"l")`      |
| 集合（`set`）   | ❌                   | 无        | 需手动遍历                       |
| 字典（`dict`）  | ❌                   | 无        | `list(d.values()).count(1)` |
| 数字（`int`）   | ❌                   | 无        | 不适用                         |

**Optional**\
`Optional[Type]` 表示变量可以是 `Type` 类型或 `None`

`Optional[Type] = Union[Type, None] = Type|None`


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nataliekung.gitbook.io/ladder_code/python-code-cheatsheet.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
