Python作为一门“全能型”编程语言,在科学计算、数据分析、算法开发等领域广泛应用,其核心优势包括:
本文将从数学运算、代码性能优化、代码复杂度分析三个维度,结合10个实战案例,深入解析Python代码计算的完整技术栈。
Python内置的math模块提供基础数学函数:
import math
# 计算平方根、对数、阶乘
sqrt_val = math.sqrt(25) # 5.0
log_val = math.log(100, 10) # 2.0
factorial_val = math.factorial(5) # 120
# 三角函数计算(弧度制)
sin_val = math.sin(math.pi / 2) # 1.0
import numpy as np
# 矩阵乘法
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
result = np.dot(matrix_a, matrix_b) # [[19 22], [43 50]]
# 快速傅里叶变换
signal = np.array([0, 1, 0, -1, 0])
fft_result = np.fft.fft(signal) # 复数数组表示频域
使用timeit模块精确测量代码片段耗时:
import timeit
# 测试列表推导式与循环的性能差异
loop_time = timeit.timeit('''
result = []
for i in range(1000):
result.append(i * 2)
''', number=1000)
list_comp_time = timeit.timeit('[i * 2 for i in range(1000)]', number=1000)
print(f"循环耗时: {loop_time:.4f}s,列表推导式耗时: {list_comp_time:.4f}s")
import cProfile
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
# 分析递归函数性能
cProfile.run('fibonacci(20)')
输出示例:
167761 function calls (4 primitive calls) in 0.045 seconds
import tracemalloc
tracemalloc.start()
# 测试列表与生成器的内存占用
def generate_data():
return [i ** 2 for i in range(100000)]
data = generate_data()
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno')[:3]:
print(stat)
# 安装cloc
pip install cloc
# 统计当前目录代码量
cloc .
输出示例:
Python 10 files 500 lines 0 comments
# 安装radon
pip install radon
# 计算函数圈复杂度
radon cc my_module.py -s
输出示例:
my_module.py
F 5:0 my_function - B (6)
from scipy import integrate
result, error = integrate.quad(lambda x: x**2, 0, 1)
print(f"积分结果: {result}, 误差: {error}") # 0.333..., 3.7e-15
from concurrent.futures import ThreadPoolExecutor
def process_data(num):
return num * 2
with ThreadPoolExecutor(max_workers=4) as executor:
results = list(executor.map(process_data, range(1000)))
from sympy import symbols, solve
x = symbols('x')
equation = x**2 - 3*x + 2
solution = solve(equation, x) # [1, 2]
from PIL import Image
img = Image.open("input.jpg")
gray_img = img.convert('L') # 转为灰度图
gray_img.save("output.jpg")
import dask.array as da
x = da.random.random((10000, 10000), chunks=(1000, 1000))
y = x.mean(axis=0).compute() # 分块计算均值
# 错误示例 ❌
print(0.1 + 0.2 == 0.3) # False
# 正确方案 ✅
from math import isclose
print(isclose(0.1 + 0.2, 0.3, rel_tol=1e-9)) # True
使用multiprocessing替代threading处理CPU密集型任务。
明确库版本(如NumPy 1.21+支持新API)。