# 等待时间分布(文本直方图) print(f"\n等待时间分布:") max_wait = max(wait_times) n_bins = 10 bin_width = max_wait / n_bins if max_wait > 0else1 bins = [0] * n_bins for w in wait_times: idx = min(int(w / bin_width), n_bins - 1) bins[idx] += 1
for i, count inenumerate(bins): bar = '█' * (count * 40 // max(bins)) lo = i * bin_width hi = (i + 1) * bin_width print(f" {lo:6.3f}-{hi:6.3f}s |{bar} ({count})")
from scipy.integrate import odeint import numpy as np
defsir_model(y, t, beta, gamma): """SIR 微分方程""" S, I, R = y dSdt = -beta * S * I dIdt = beta * S * I - gamma * I dRdt = gamma * I return [dSdt, dIdt, dRdt]
defbuild_markov_chain(text, order=2): """ 构建 n 阶马尔可夫链 order: 阶数(看前几个词预测下一个) """ words = text.split() chain = defaultdict(list)
for i inrange(len(words) - order): state = tuple(words[i:i + order]) next_word = words[i + order] chain[state].append(next_word)
return chain
defgenerate_text(chain, order=2, length=50): """用马尔可夫链生成文本""" # 随机选一个起始状态 state = random.choice(list(chain.keys())) result = list(state)
for _ inrange(length): if state notin chain: break next_word = random.choice(chain[state]) result.append(next_word) state = tuple(result[-order:])
return' '.join(result)
# 用一段技术文本做训练语料 corpus = """ the server receives a request and processes it the server sends a response back to the client the client sends a request to the server the server checks the cache before querying the database the database returns the result to the server the server stores the result in the cache the client receives the response and renders the page the load balancer distributes requests to multiple servers the server processes the request and returns a response the cache stores frequently accessed data for fast retrieval the database stores persistent data and handles queries the server handles concurrent requests using a thread pool the client sends multiple requests in parallel the server returns an error if the request is invalid the load balancer checks server health before routing """
chain = build_markov_chain(corpus, order=2)
print("=== 二阶马尔可夫链文本生成 ===\n") print("训练语料: 后端技术描述文本\n") print("生成结果(每次不同):") for i inrange(5): text = generate_text(chain, order=2, length=15) print(f" {i+1}. {text}")
for i inrange(n): name, weight, value = items[i] # 从大到小遍历(0/1背包的关键!避免重复选择) for j inrange(capacity, weight - 1, -1): if dp[j - weight] + value > dp[j]: dp[j] = dp[j - weight] + value chosen[i][j] = True
# 回溯找选了哪些物品 selected = [] j = capacity for i inrange(n - 1, -1, -1): if chosen[i][j]: selected.append(items[i]) j -= items[i][1]
print(f"总预算: {budget} 万") print(f"\n可选安全措施:") print(f"{'措施':<16}{'成本(万)':>8}{'风险降低':>8}{'性价比':>8}") print("-" * 44) for name, cost, value in security_items: ratio = value / cost print(f"{name:<16}{cost:>8}{value:>8}{ratio:>8.2f}")
max_value, selected = knapsack_01(security_items, budget) total_cost = sum(item[1] for item in selected)
print(f"\n最优方案 (总预算 {budget} 万):") print(f"{'='*40}") for name, cost, value in selected: print(f" ✓ {name}: {cost}万 → 风险降低 {value}") print(f"{'='*40}") print(f"总成本: {total_cost} 万") print(f"总风险降低: {max_value}") print(f"剩余预算: {budget - total_cost} 万")
练习题
题1:排队论计算
一个 API 服务每秒收到 100 个请求(λ=100),每个请求平均处理 8ms(μ=125/秒)