算法实战
综合实战:用算法解决真实业务问题。三个场景:搜索推荐排序、日志去重计数、最短路径。每个场景对应一类算法。
场景
- 按热度排序商品 → 排序算法
- 统计 1 亿日志中独立 IP → 哈希/位图
- 地图导航最短路线 → BFS/Dijkstra
代码示例
import heapq
from collections import Counter
# 场景1:商品按综合热度排序
products = [
{"name": "苹果", "sales": 100, "score": 4.8},
{"name": "香蕉", "sales": 200, "score": 4.5},
{"name": "橘子", "sales": 150, "score": 4.9},
]
products.sort(key=lambda p: (p["sales"], p["score"]), reverse=True)
print("热销榜:", [p["name"] for p in products])
# 场景2:日志独立 IP 统计
logs = ["192.168.1.1", "192.168.1.2", "192.168.1.1", "10.0.0.1"]
print("独立IP数:", len(set(logs))) # 3
print("频次:", Counter(logs).most_common(2))
# 场景3:Dijkstra 最短路径(简化版)
def dijkstra(graph, start):
dist = {node: float("inf") for node in graph}
dist[start] = 0
pq = [(0, start)] # 最小堆
while pq:
d, node = heapq.heappop(pq)
if d > dist[node]:
continue
for nxt, w in graph[node].items():
if d + w < dist[nxt]:
dist[nxt] = d + w
heapq.heappush(pq, (dist[nxt], nxt))
return dist
graph = {
"A": {"B": 1, "C": 4},
"B": {"A": 1, "C": 2, "D": 5},
"C": {"A": 4, "B": 2, "D": 1},
"D": {"B": 5, "C": 1},
}
print("A到各点最短:", dijkstra(graph, "A"))
📚 Python 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
print("hello") | 输出到控制台 |
name = "张三" | 变量赋值(无需声明类型) |
if x > 0: ... | 条件判断(注意冒号和缩进) |
for i in range(10): ... | 循环(缩进是语法的一部分) |
while x < 10: ... | 条件循环 |
def fn(a, b): return a + b | 定义函数 |
class Person: ... | 定义类 |
list = [1, 2, 3] | 列表(可改) |
tuple = (1, 2) | 元组(不可改) |
dict = {"key": "value"} | 字典(键值对) |
set = {1, 2, 3} | 集合(去重) |
len(obj) | 取长度 |
str(x) / int(x) / float(x) | 类型转换 |
s.split(",") | 字符串按分隔符拆分 |
" ".join(list) | 列表拼接成字符串 |
import os | 导入模块 |
from math import sqrt | 从模块导入指定函数 |
try: ... except Exception as e: ... | 异常捕获 |
with open("a.txt", "r") as f: ... | 文件读取(自动关闭) |
f"你好 {name}" | f-string 格式化 |
lambda x: x * 2 | 匿名函数 |
list(map(fn, arr)) | 函数式处理列表 |
range(start, stop, step) | 生成数字序列 |
if __name__ == "__main__": | 主入口判断 |
pip install 包名 | 安装第三方包(命令行) |