defaultdict(int)函数
该函数用于构建一个字典对象,通常用于实现key的计数功能;
set()函数
该函数用来创造一个元素无序不重复的哈希表;
位运算
x = ord(ch) - ord(“a”)
if seen & (1 << x): return ch
seen |= (1 << x)
具体代码知识点
h = Counter(num) #Counter哈希表实现计数功能
for idx, v in enumerate(num): #enumerate返回可迭代对象的索引和值
mapping = defaultdict(lambda : '?', knowledge) #lambda函数返回knowledge的值
return ''.join(res) #jion函数将res内元素连接生成一个新字符串
for c, cnt in Counter(target).items(): #items函数将字典遍历返回key,value键值对
return res % (10 ** 9 + 7) #10**9是10的9次幂
j = int(str(i)[::-1]) #将整数 i 各个数字位反转
isdigit()函数
检测字符串是否只由数字组成,(0和正数)
all()函数
判断可迭代对象是否全符合条件,返回true或false
return all(
a < b for a, b in itertools.pairwise(
map(
int.__call__,
filter(
str.isdigit,
s.split()
)
)
)
)
itertools.pairwise() python3.10的特性 用来获取连续的重叠对 比如[1,2,3,4] 则输出12 23 34
map()两个参数 第一个参数为函数 第二个参数为序列 针对序列每个元素调用函数 返回新列表
int.__ call __(x) 等同于int(x)
filter() 第一个参数为判断函数,第二个参数为可迭代对象,用来过滤掉不符合条件的元素,返回一个列表
Trie,前缀树,字典树
应用:前缀匹配;词频统计(也可以用哈希表)
实现代码
class Trie:
def __init__(self):
self.children = [None] * 26
self.isEnd = False
def searchPrefix(self, prefix: str) -> "Trie":
node = self
for ch in prefix:
ch = ord(ch) - ord("a")
if not node.children[ch]:
return None
node = node.children[ch]
return node
def insert(self, word: str) -> None:
node = self
for ch in word:
ch = ord(ch) - ord("a")
if not node.children[ch]:
node.children[ch] = Trie()
node = node.children[ch]
node.isEnd = True
def search(self, word: str) -> bool:
node = self.searchPrefix(word)
return node is not None and node.isEnd
def startsWith(self, prefix: str) -> bool:
return self.searchPrefix(prefix) is not None