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
nodeInfo = dict()
nodeInfo[ng] = nodeInfo.get(ng, 0) + 1 #有则返回vaL 无则返回0 这样可以无需初始化
如何统计字典中某个值的出现次数?
用 list(dict.values()).count(x)
🔍 parent.get(key) vs parent[key]
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: 97sort 自定义函数
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 4default: Functions: max() and min() support the default parameter.
min/max([], default=0)  # Returns 0
遍历dictionary:
```python
for k,v in d.items():
    v.reserse() #v is a list
```number char coversion
char.isdigit() 
char.isalpha()
 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
 Counter(list)  returnr dict.
 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上
#滤掉所有非(),因为count返回返回1或0
s = "a(b)c)d"
result = ''.join(filter('()'.count, s))
print(result)  # Output: "()()"
Concise code
1️⃣ Multiple Appends in One Line
Instead of:
pythonCopyEditqueue.append(item1)
queue.append(item2)Use:
pythonCopyEditqueue.extend([item1, item2])Or:
pythonCopyEditqueue += item1, item2  # No need for extra brackets!2️⃣ Inline If-Else (or Trick)
Instead of:
pythonCopyEditif name:
    greeting = name
else:
    greeting = "Guest"Use:
pythonCopyEditgreeting = name or "Guest"- If - nameis- Noneor- "", it defaults to- "Guest".
3️⃣ Swapping Variables Without Temp
Instead of:
pythonCopyEdittemp = a
a = b
b = tempUse:
pythonCopyEdita, b = b, a4️⃣ List Comprehension Instead of Loops
Instead of:
pythonCopyEditsquares = []
for i in range(10):
    squares.append(i * i)Use:
pythonCopyEditsquares = [i * i for i in range(10)]5️⃣ Using defaultdict to Avoid Key Errors
Instead of:
pythonCopyEditword_count = {}
for word in words:
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1Use:
pythonCopyEditfrom collections import defaultdict
word_count = defaultdict(int)
for word in words:
    word_count[word] += 16️⃣ Merging Two Dictionaries
Instead of:
pythonCopyEditdict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1.copy()
merged.update(dict2)Use (Python 3.9+):
pythonCopyEditmerged = dict1 | dict27️⃣ Unpacking Iterables
Instead of:
pythonCopyEdita = my_list[0]
b = my_list[1]
c = my_list[2:]Use:
pythonCopyEdita, b, *c = my_listBIT
bin(mask)
转二进制字符串(带 0b 前缀)
'0b101'
mask.bit_count()
直接统计 1 的个数(Python 3.10+)
2(若 mask = 0b1010)
pos = available & -available 的作用:取最低位的 1
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
Last updated
Was this helpful?