I have to program a way to calculate binomial distribution in Python for pi as 0.1, 0.5 and 0.9. The desired input and output are as follows:
input: 3
output:
[0.729, 0.243, 0.027, 0.001]
[0.125, 0.375, 0.375, 0.125]
[0.001, 0.027, 0.243, 0.729]
I have written the code but I can't seem to figure out how to have both brackets and commas in my output. This is the code:
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:])
You can use str.join()
to do this sort of thing.
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:])
Result:
[0.729, 0.243, 0.027, 0.001]
[0.125, 0.375, 0.375, 0.125]
[0.001, 0.027, 0.243, 0.729]