Find probability of selecting element from kth column after N iterations | Python3 implementation of the above approach ; Function to calculate probability ; declare dp [ ] [ ] and sum [ ] ; precalculate the first row ; calculate the probability for each element and update dp table ; return result ; Driver code
n = 4 NEW_LINE m = 4 NEW_LINE def calcProbability ( M , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( m ) ] NEW_LINE Sum = [ 0 for i in range ( n ) ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT dp [ 0 ] [ j ] = M [ 0 ] [ j ] NEW_LINE Sum [ 0 ] += dp [ 0 ] [ j ] NEW_LINE DEDENT for i in range ( 1 , m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT dp [ i ] [ j ] += ( dp [ i - 1 ] [ j ] / Sum [ i - 1 ] + M [ i ] [ j ] ) NEW_LINE Sum [ i ] += dp [ i ] [ j ] NEW_LINE DEDENT DEDENT return dp [ n - 1 ] [ k - 1 ] / Sum [ n - 1 ] NEW_LINE DEDENT M = [ [ 1 , 1 , 0 , 3 ] , [ 2 , 3 , 2 , 3 ] , [ 9 , 3 , 0 , 2 ] , [ 2 , 3 , 2 , 2 ] ] NEW_LINE k = 3 NEW_LINE print ( calcProbability ( M , k ) ) NEW_LINE