python刷题好用的一些方法总结

优先队列

import heapq a = [] nums = 0 # 数字,默认是小根堆 从小到大排序 heapq.heappush(a,nums) heapq.heappop(a) # 弹出堆顶

#heapq.heapfy(list) 将一个列表转换为小根堆 #heappushpop(heap,item) 同时pop以及添加item,先push,再pop #heapreplace(heap.item) 先pop,再push

heapq.heapify(x): O(n)
heapq.heappush(heap, item): O(logn)
heapq.heappop(heap): O(logn)

collections

元组比列表更简洁

Counter

字典的字类,提供了可哈希对象的计数功能 from collections import Counter 统计元素出现次数

defaultdict

字典的字类,提供了一个工厂函数,为字典查询提供了默认值 from collections import defaultdict

OrderedDict

字典的字类,保留了他们被添加的顺序 from collections import OrderedDict() c = OrderedDict()

deque

from collections import deque

函数名 解释 append(x) 添加x到右端 appendleft(x) 添加x到左端 clear() 清楚所有元素,长度变为0 copy() 创建一份浅拷贝 count(x) 计算队列中个数等于x的元素 extend(iterable) 在队列右侧添加iterable中的元素 extendleft(iterable) 在队列左侧添加iterable中的元素,注:在左侧添加时,iterable参数的顺序将会反过来添加 index(x[,start[,stop]]) 返回第 x 个元素(从 start 开始计算,在 stop 之前)。返回第一个匹配,如果没找到的话,升起 ValueError 。 insert(i,x) 在位置 i 插入 x 。注:如果插入会导致一个限长deque超出长度 maxlen 的话,就升起一个 IndexError 。 pop() 移除最右侧的元素 popleft() 移除最左侧的元素 remove(value) 移去找到的第一个 value。没有抛出ValueError reverse() 将deque逆序排列。返回 None 。 maxlen 队列的最大长度,没有限定则为None。

namedtuple

创建命名元组子类的工厂函数

from collections import namedtuple
Person = namedtuple(Person, [age, height, name])
Human = namedtuple(Human, age, height, name)
Human2 = namedtuple(Human2, age height name)
tom = Person(30,178,Tom)
jack = Human(20,179,Jack)
tom
Person(age=30, height=178, name=Tom)
 jack
Human(age=20, height=179, name=Jack)
tom.age #直接通过  实例名+.+属性 来调用
30
jack.name
Jack

整数变二进制,二进制变整数

python bin()函数 bin 函数可以把一个数转化为二进制数 int(str(num),2) 将二进制数转化为整数

字母变数字,数字变字母

py将字母变成数字的内置函数 ord(‘F’) = 70 chr(70) = ‘F’

设置递归深度

python 设置递归深度 import sys sys.setrecursionlimit(1000)

读到文件结束

try:
	while True:
		s = input()
except EOFError: 
	pass

python 重定向

import sys
files = open(test.txt, r) 从文件中读(使用input()读入)
sys.stdin = files
file = open(test2.txt, w)
sys.stdout = file  # 标准输出重定向至文件

try:
	while True:
		s = input() # 从test.txt中读取数据
		print(s) # 存入test2.txt文件中
except EOFError: 
	pass
files.close()
file.close()
经验分享 程序员 微信小程序 职场和发展