0

我必须编写一种方法来计算 Python 中 pi 的二项式分布为 0.1、0.5 和 0.9。所需的输入和输出如下:

输入:3

输出:

[0.729, 0.243, 0.027, 0.001]

[0.125, 0.375, 0.375, 0.125]

[0.001, 0.027, 0.243, 0.729]


我已经编写了代码,但我似乎无法弄清楚如何在我的输出中同时包含括号和逗号。这是代码:

import numpy as np
import math
n = int(input())
pi = [0.1, 0.5, 0.9]
dist = []
result = []

for i in pi:
    for j in range(0, n+1):
        dist.append(math.comb(n, j) * (i**j) * ((1-i)**(n-j)))

for i in dist:
    result.append(round(i, 3))

result = np.array(result)

print(result[:n+1])
print(result[n+1: 2*n+2])
print(result[2*n+2:])
4

1 回答 1

0

你可以str.join()用来做这种事情。

def print_pretty(result):
    print("[" + ", ".join(str(value) for value in result) + "]")
    
print_pretty(result[:n+1])
print_pretty(result[n+1: 2*n+2])
print_pretty(result[2*n+2:])

结果:

[0.729, 0.243, 0.027, 0.001]
[0.125, 0.375, 0.375, 0.125]
[0.001, 0.027, 0.243, 0.729]
于 2021-05-08T19:05:01.287 回答