text: Probability of distributing given balls into two halves having equal count of distinct colors | Stores the count of distinct colors in box1 ; Stores the count of distinct colors in box2 ; Function to calculate the required probability ; Calculate factorial from [ 1 , 10 ] ; Assign all distinct balls to second box ; Total number of balls ; Calculate total number of balls ; If K is an odd number ; Total ways of distributing the balls in two equal halves ; Required number of ways ; Return the required probability ; Function to calculate total number of possible distributions which satisfies the given conditions ; If used balls is equal to K / 2 ; If box1 is equal to box2 ; Base condition ; Stores the number of ways of distributing remaining balls without including the current balls in box1 ; Increment box1 by one ; Iterate over the range [ 1 , balls [ i ] ] ; If all the balls goes to box1 , then decrease box2 by one ; Total number of ways of selecting j balls ; Increment res by total number of valid ways of distributing the remaining balls ; Decrement box1 by one ; Increment box2 by 1 ; Function to calculate factorial of N ; Base Case ; Iterate over the range [ 1 , N ] ; Function to calculate NcR ; Driver Code ; Print the result
code: box1 = 0 NEW_LINE box2 = 0 NEW_LINE fact = [ 0 for i in range ( 11 ) ] NEW_LINE def getProbability ( balls ) : NEW_LINE INDENT global box1 , box2 , fact NEW_LINE factorial ( 10 ) NEW_LINE box2 = len ( balls ) NEW_LINE K = 0 NEW_LINE for i in range ( len ( balls ) ) : NEW_LINE INDENT K += balls [ i ] NEW_LINE DEDENT if ( K % 2 == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT all = comb ( K , K // 2 ) NEW_LINE validPermutation = validPermutations ( K // 2 , balls , 0 , 0 ) NEW_LINE return validPermutation / all NEW_LINE DEDENT def validPermutations ( n , balls , usedBalls , i ) : NEW_LINE INDENT global box1 , box2 , fact NEW_LINE if ( usedBalls == n ) : NEW_LINE INDENT if ( box1 == box2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( i >= len ( balls ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = validPermutations ( n , balls , usedBalls , i + 1 ) NEW_LINE box1 += 1 NEW_LINE for j in range ( 1 , balls [ i ] + 1 ) : NEW_LINE INDENT if ( j == balls [ i ] ) : NEW_LINE INDENT box2 -= 1 NEW_LINE DEDENT combinations = comb ( balls [ i ] , j ) NEW_LINE res += combinations * validPermutations ( n , balls , usedBalls + j , i + 1 ) NEW_LINE DEDENT box1 -= 1 NEW_LINE box2 += 1 NEW_LINE return res NEW_LINE DEDENT def factorial ( N ) : NEW_LINE INDENT global box1 , box2 , fact NEW_LINE fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE DEDENT DEDENT def comb ( n , r ) : NEW_LINE INDENT global box1 , box2 , fact NEW_LINE res = fact [ n ] // fact [ r ] NEW_LINE res //= fact [ n - r ] NEW_LINE return res NEW_LINE DEDENT arr = [ 2 , 1 , 1 ] NEW_LINE N = 4 NEW_LINE print ( getProbability ( arr ) ) NEW_LINE