Probability of getting at least K heads in N tosses of Coins | Naive approach in Python3 to find probability of at least k heads ; Returns probability of getting at least k heads in n tosses . ; Probability of getting exactly i heads out of n heads ; Note : 1 << n = pow ( 2 , n ) ; Preprocess all factorial only upto 19 , as after that it will overflow ; Driver code ; Probability of getting 2 head out of 3 coins ; Probability of getting 3 head out of 6 coins ; Probability of getting 12 head out of 18 coins
MAX = 21 NEW_LINE fact = [ 0 ] * MAX NEW_LINE def probability ( k , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( k , n + 1 ) : NEW_LINE INDENT ans += fact [ n ] / ( fact [ i ] * fact [ n - i ] ) NEW_LINE DEDENT ans = ans / ( 1 << n ) NEW_LINE return ans NEW_LINE DEDENT def precompute ( ) : NEW_LINE INDENT fact [ 0 ] = 1 NEW_LINE fact [ 1 ] = 1 NEW_LINE for i in range ( 2 , 20 ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT precompute ( ) NEW_LINE print ( probability ( 2 , 3 ) ) NEW_LINE print ( probability ( 3 , 6 ) ) NEW_LINE print ( probability ( 12 , 18 ) ) NEW_LINE DEDENT