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
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()
下一篇:
js原型对象及常见使用情况