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
如何统计字典中某个值的出现次数?
用 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)
数组slicing
reverse : s[::-1] start:stop:step
二维数组
Ord(): return unicode code point of a charactor
sort 自定义函数
*list will unpack the list
default: Functions: max()
and min()
support the default
parameter.
遍历dictionary:
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.
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 returnsNone
.
Sorting a List
Sorting a Dictionary by Value
Sorting a List of Dictionaries
deque
整个list 加入deque, extend()
use cache in DP
filter
参数是一个函数和iterator,函数作用在每个iterator上
Concise code
1️⃣ Multiple Appends in One Line
Instead of:
Use:
Or:
2️⃣ Inline If-Else (or
Trick)
Instead of:
Use:
If
name
isNone
or""
, it defaults to"Guest"
.
3️⃣ Swapping Variables Without Temp
Instead of:
Use:
4️⃣ List Comprehension Instead of Loops
Instead of:
Use:
5️⃣ Using defaultdict
to Avoid Key Errors
Instead of:
Use:
6️⃣ Merging Two Dictionaries
Instead of:
Use (Python 3.9+):
7️⃣ Unpacking Iterables
Instead of:
Use:
BIT
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?