Probability of getting more heads than tails when N biased coins are tossed | Python3 implementation of the above approach ; Function to return the probability when number of heads is greater than the number of tails ; Declaring the DP table ; Base case ; Iterating for every coin ; j represents the numbers of heads ; If number of heads is equal to zero there there is only one possibility ; When the number of heads is greater than ( n + 1 ) / 2 it means that heads are greater than tails as no of tails + no of heads is equal to n for any permutation of heads and tails ; Driver Code ; 1 based indexing ; Number of coins ; Function call
import numpy as np NEW_LINE def Probability ( p , n ) : NEW_LINE INDENT dp = np . zeros ( ( n + 1 , n + 1 ) ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = 0.0 NEW_LINE DEDENT DEDENT dp [ 0 ] [ 0 ] = 1.0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] * ( 1.0 - p [ i ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i - 1 ] [ j ] * ( 1.0 - p [ i ] ) + dp [ i - 1 ] [ j - 1 ] * p [ i ] ) ; NEW_LINE DEDENT DEDENT DEDENT ans = 0.0 ; NEW_LINE for i in range ( ( n + 1 ) // 2 , n + 1 ) : NEW_LINE INDENT ans += dp [ n ] [ i ] ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p = [ 0.0 , 0.3 , 0.4 , 0.7 ] ; NEW_LINE n = len ( p ) - 1 ; NEW_LINE print ( Probability ( p , n ) ) ; NEW_LINE DEDENT