用列表推导式和生成式改写下面这段代码def monte_carlo(dim, N): v = 1 for i in range(dim): v *= 2 s = 0 for i in range(N): x = [random.uniform(0,1) for j in range(dim)] s += f(x) return s * v / N
时间: 2023-11-29 20:04:38 浏览: 89
Python列表推导式实现代码实例
可以这样改写:
v = 2 ** dim
s = sum(f([random.uniform(0, 1) for _ in range(dim)]) for _ in range(N))
result = s * v / N
使用生成式:
v = 2 ** dim
s = sum(f([random.uniform(0, 1) for _ in range(dim)]) for i in range(N))
result = s * v / N
使用列表推导式:
v = 2 ** dim
s = sum([f([random.uniform(0, 1) for j in range(dim)]) for i in range(N)])
result = s * v / N
阅读全文