文章目录
1. 处理输入
[list/tuple/dict(input().split()) for _ range(N)] # 对应有N行输入
map(int, input().split()) # 批量转换成int
2. 经典题目
计算器
3. 常用函数方法
3.1 列表推导式
new_list = [expression for item in iterable if condition]
- expression 是对每个元素执行的操作。
- item 是迭代中的当前项。
- iterable 是可迭代对象,如列表、元组、字符串等。
- if condition 是可选的过滤条件。
a.基本用法
squares = [x**2 for x in range(10)]
print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
b.带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # 输出: [0, 4, 16, 36, 64]
c.嵌套列表推导式
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
flattened_matrix = [num for row in matrix for num in row]
print(flattened_matrix) # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]
d.复杂表达式
words = ['apple', 'banana', 'cherry']
word_lengths = [(word, len(word)) for word in words]
print(word_lengths) # 输出: [('apple', 5), ('banana', 6), ('cherry', 6)]
3.2 .sort() / sorted() 的 key
a.字符串列表按长度排序
words = ['banana', 'pie', 'apple', 'cherry']
words.sort(key=len)
print(words) # 输出: ['pie', 'apple', 'banana', 'cherry']
b.字典列表按照特定键排序
people = [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25},
{'name': 'Charlie', 'age': 35}
]
# 按年龄升序排列
people.sort(key=lambda person: person['age'])
print(people)
# 输出:
# [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]
c.使用itemgetter进行排序
当需要根据多个字段进行排序时,可以使用operator.itemgetter,它比lambda函数更高效。
from operator import itemgetter
people = [
{'name': 'Alice', 'age': 30, 'height': 165},
{'name': 'Bob', 'age': 25, 'height': 175},
{'name': 'Charlie', 'age': 30, 'height': 180}
]
# 先按年龄,再按身高排序
people.sort(key=itemgetter('age', 'height'))
print(people)
# 输出:
# [{'name': 'Bob', 'age': 25, 'height': 175}, {'name': 'Alice', 'age': 30, 'height': 165}, {'name': 'Charlie', 'age': 30, 'height': 180}]
3.3 .is[ anything ] ()函数
.isdigit()
:检查是否只包含数字.isalpha()
:检查是否只包含字母.isupper()
:检查是否只包含大写字母.islower()
:检查是否只包含小写字母.isalnum()
:检查是否只包含字母或数字.lower()
:将字符串中的所有大写字母转换为小写字母。.upper()
:将字符串中的所有小写字母转换为大写字母
3.4 chr() / ord()
3.5 divmod()
4 常用算法
4.1 二分查找
def binary_search(nums, target):
left = 0
right = len(nums) - 1 # 初始化右边界为数组最后一个索引
while left <= right: # 循环条件:当 left 小于等于 right 时继续循环
mid = (left + right) // 2 # 计算中间位置
if nums[mid] == target:
return mid # 找到目标值,返回其索引
elif nums[mid] < target:
left = mid + 1 # 目标值在右半部分
else:
right = mid - 1 # 目标值在左半部分
return -1 # 如果没有找到目标值,返回 -1
4.2 矩阵4个方向扩散
while stack:
x, y = stack.pop()
if -1 < x < m and -1 < y < n and not visited[x][y] and digit_sum(x) + digit_sum(y) <= k:
visited[x][y] = True
ans += 1
stack.extend([(x-1, y), (x+1, y), (x, y-1), (x, y+1)])
4.3 visited数组表示有无访问
4.4 哈夫曼树
5 常用数据结构的实现
5.1 树
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val # 节点存储的值
self.left = left # 左子节点
self.right = right # 右子节点
5.2 链表
class ListNode:
def __init__(self, value=0, next=None):
self.value = value # 节点存储的值
self.next = next # 指向下一个节点的指针