【参考:Python3数据结构:力扣Leetcode预备知识【已完结】_哔哩哔哩_bilibili】
【参考:【python】 程序设计基础_myaijarvis的博客-CSDN博客】
【参考:Python 标准库 — Python 3.7.13 文档】
- 语言选择:
刷LeetCode 选择哪个都行,哪个方便用哪个,因为不同语言的限时不一样
打比赛一般限时都一样,所以首选C++,其次是Java
- 其他文章:
【参考:【Python】刷题技巧总结(比较 排序)_myaijarvis的博客-CSDN博客】
【参考:【Python】技巧总结(数据结构)-CSDN博客】
技巧
采用内置函数
len()
sum()
count()
# 最大值
x=float("inf") # infinity
# 最小值
y=float("-inf")
print(x) # inf
print(y) # -inf
- zip
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
# zip可以将多个列表、元组或其它序列成对组合成一个元组列表:
for k in zip(arr1, arr2):
print(k)
"""
(1, 4)
(2, 5)
(3, 6)
"""
result = []
for i, j in zip(arr1, arr2):
result.append(i)
result.append(j)
print(result) # [1, 4, 2, 5, 3, 6]
数据类型
【参考:Python六大基本数据类型_迷鹿小女子的博客-CSDN博客】
整型(int) - 通常被称为是整型或整数,是正或负整数,不带小数点。Python3 整型是没有限制大小的,可以当作 Long 类型使用
int
float
complex
print(3/2)
print(3//2)
print(1/3)
"""
1.5
1
0.3333333333333333
"""
bool
False True
int 0 非0
float 0.0 非0.0
str '' 空字符串 非空字符串
列表 [] 空列表
元组 ()
字典 {}
数学函数
abs(x):x的绝对值【内置函数】
pow(x,y):
x
y
x^y
xy
print(abs(-1)) # 1
print(abs(-1.0)) # 1.0
print(pow(2, 3)) # 8
print(pow(2.0, 3)) # 8.0
print(pow(2, 3.0)) # 8.0
math包
pow(x,y):
x
y
x^y
xy
sqrt(x):
x
\sqrt{x}
x
from math import sqrt,pow,fabs
# 全部返回float类型
print(sqrt(4))
print(pow(4,2))
print(fabs(-4)) # 和abs函数一样
"""
2.0
16.0
4.0
"""
字符串
【参考:内置类型 str — Python 3.7.13 文档】
s = ' Hello world '
# 'd'第一次出现的位置,找不到时会引发 ValueError
print(s.index('d')) # 11
# 找到'd'第一次出现的位置,未被找到则返回 -1
print(s.find('d')) # 11
# 'l'出现的次数
print(s.count('l')) # 3
print(s.strip()) # 'Hello world'
print(s.upper()) # ' HELLO WORLD '
print(s.lower()) # ' hello world '
print(s.split(' ')) # ['', 'Hello', 'world', '']
# 逆置(自身不改变)
print(s[::-1]) # ' dlrow olleH '
列表
更多排序请【参考:【Python】刷题技巧总结(比较 排序)_myaijarvis的博客-CSDN博客】
arr = [1, 4, 3, 2, 5]
arr.append(6)
print(arr) # [1, 4, 3, 2, 5, 6]
x = arr.pop() # 默认删除最后一个
print(x) # 6
y = arr.pop(0) # 删除第一个
print(y) # 0
arr.sort() # 原地排序,默认升序
print(arr) # [2, 3, 4, 5]
arr.reverse() # 原地逆置 arr.sort(reverse=True)
print(arr) # [5, 4, 3, 2]
b=sorted(arr,reverse=True) # 不改变自身,返回排序后的列表
print(b) # [2, 3, 4, 5]
元组
定义完成后只能查询
可以和列表一样切片访问
a=(1,2,3) # a=tuple([1,2,3]) # 传入一个可迭代的变量
print(a.index(2)) # 1
print(1 in a) # True
print(a[0]) # 1
b=(1,) # 一个元素的元组
print(b) # (1,)
d=tuple() # 空元组
print(d) # ()
e=() # 空元组
print(e) # ()
集合
交集 & : x&y,返回一个新的集合,包括同时在集合 x 和y中的共同元素。
并集 | : x|y,返回一个新的集合,包括集合 x 和 y 中所有元素。
差集 - : x-y,返回一个新的集合,包括在集合 x 中但不在集合 y 中的元素。
补集 ^ : x^y,返回一个新的集合,包括集合 x 和 y 的非共同元素。
a = set() # 空集合只能这样定义,
# 非空可以a={1,2,3}
# a=set([1,2,3]) # 传入一个可迭代的变量
# a=set(3)
a.add(1)
a.update([3, 5]) # 更新集合,添加来自 others 中的所有元素。
# 相当于并集 &
# print(a & set([3,5]) )
# print(a & {3,5} )
print(a) # {1, 3, 5}
a.remove(3) # 删除3
print(a) # {1, 5}
print(1 in a) # True
字典
【参考:内置类型 dict — Python 3.7.13 文档】
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e # True
a = dict() # a={}
print(a) # {}
# 增
a['a']='aa'
a['b']='bb'
a['c']='cc'
a.update({'f':'ff'})
print(a) # {'a': 'aa', 'b': 'bb', 'c': 'cc', 'f': 'ff'}
# 改
a.update({'a':'aaa'})
a['b']='bbb'
print(a) # {'a': 'aaa', 'b': 'bbb', 'c': 'cc', 'f': 'ff'}
# 删
print(a.pop('a')) # aaa
# 不存在该键就返回默认值
print(a.pop('d','dd')) # dd
print(a) # {'b': 'bbb', 'c': 'cc', 'f': 'ff'}
# 查
print(a['b']) # bbb
print(a.keys()) # dict_keys(['b', 'c', 'f'])
print(a.values()) # dict_values(['bbb', 'cc', 'ff'])
print(a.items()) # dict_items([('b', 'bbb'), ('c', 'cc'), ('f', 'ff')])
队列
【参考:collections — 容器数据类型 — Python 3.7.13 文档】
使用deque双向队列,(不要用list,头部插入为O(n))
from collections import deque
arr = [i for i in range(1, 6)]
q = deque(arr)
print(q)
# deque([1, 2, 3, 4, 5])
# 头 尾
q.append(6) # 尾部 右侧
q.appendleft(0) # 头部 左侧
print(q) # deque([0, 1, 2, 3, 4, 5, 6])
x = q.popleft() # 头部 左侧
y = q.pop() # 尾部 右侧
print(x) # 0
print(y) # 6
print(q) # deque([1, 2, 3, 4, 5])
front: int = q[0] # 队首元素
rear: int = q[-1] # 队尾元素
size: int = len(q)
栈
使用List表示Stack
stack = [] # or stack=list()
stack.append(1) # 元素入栈(添加至栈顶)
stack.append(2)
stack.append(3)
print(stack) # [1, 2, 3]
x = stack.pop() # 栈顶元素出栈
print(x) # 3
print(stack) # [1, 2]
top = stack[-1] # 访问栈顶元素
print(top) # 2
堆
【参考:heapq — 堆队列算法 — Python 3.7.13 文档】
Python 的 heapq 模块默认实现小顶堆
考虑将“元素取负”后再入堆,这样就可以将大小关系颠倒,从而实现大顶堆
使用 list
from heapq import heapify, heappop, heappush, nlargest, nsmallest
arr = [2, 1, 5, 4, 3]
heapify(arr) # 原地转化为小顶堆 用不用都可以,只要后面使用了heappush、heappop
print(type(arr)) # 还是<class 'list'>
print(arr) # [1, 2, 5, 4, 3]
heappush(arr, 6)
print(arr) # [1, 2, 5, 4, 3, 6]
x = heappop(arr)
print(x) # 1
print(arr) # [2, 3, 5, 4, 6]
print(arr[0]) # 堆顶 1
print(nlargest(3, arr)) # n个最大的 [6, 5, 4]
print(nsmallest(3, arr)) # n个最小的 [2, 3, 4]
print(len(arr)) # 5
大顶堆
from heapq import heapify, heappop, heappush, nlargest, nsmallest
arr = [2, 1, 5, 4, 3]
arr = [i * -1 for i in arr] # 转化为大顶堆先把所有数*-1
heapify(arr)
print(arr) # [-5, -4, -2, -1, -3]
heappush(arr, 6 * -1) # 加入的数也要*-1
print(arr) # [-6, -4, -5, -1, -3, -2]
x = heappop(arr) * -1
print(x) # 6
print(arr) # [-5, -4, -2, -1, -3]
哈希表
使用dict实现
【参考:第 6 章 哈希表 - Hello 算法】
代码来源于
https://github.dev/krahets/hello-algo/tree/main/codes
python/chapter_hashing/hash_map.py
def print_dict(hmap: dict):
"""Print a dict"""
for key, value in hmap.items():
print(key, "->", value)
# 初始化哈希表
hmap = dict() # dict[int, str]
# 添加操作
# 在哈希表中添加键值对 (key, value)
hmap[12836] = "小哈"
hmap[15937] = "小啰"
hmap[16750] = "小算"
hmap[13276] = "小法"
hmap[10583] = "小鸭"
print("\n添加完成后,哈希表为\nKey -> Value")
print_dict(hmap)
# 查询操作
# 向哈希表输入键 key ,得到值 value
name: str = hmap[15937]
print("\n输入学号 15937 ,查询到姓名 " + name)
# 删除操作
# 在哈希表中删除键值对 (key, value)
hmap.pop(10583)
print("\n删除 10583 后,哈希表为\nKey -> Value")
print_dict(hmap)
# 遍历哈希表
print("\n遍历键值对 Key->Value")
for key, value in hmap.items():
print(key, "->", value)
print("\n单独遍历键 Key")
for key in hmap.keys():
print(key)
print("\n单独遍历值 Value")
for val in hmap.values():
print(val)
添加完成后,哈希表为
Key -> Value
12836 -> 小哈
15937 -> 小啰
16750 -> 小算
13276 -> 小法
10583 -> 小鸭
输入学号 15937 ,查询到姓名 小啰
删除 10583 后,哈希表为
Key -> Value
12836 -> 小哈
15937 -> 小啰
16750 -> 小算
13276 -> 小法
遍历键值对 Key->Value
12836 -> 小哈
15937 -> 小啰
16750 -> 小算
13276 -> 小法
单独遍历键 Key
12836
15937
16750
13276
单独遍历值 Value
小哈
小啰
小算
小法
二叉树
【参考:7.1 二叉树 - Hello 算法】