Count the number of special permutations | function to return the number of ways to chooser objects out of n objects ; function to return the number of degrangemnets of n ; function to return the required number of permutations ; ways to chose i indices from n indices ; Dearrangements of ( n - i ) indices ; Driver Code
def nCr ( n , r ) : NEW_LINE INDENT ans = 1 NEW_LINE if r > n - r : NEW_LINE INDENT r = n - r NEW_LINE DEDENT for i in range ( r ) : NEW_LINE INDENT ans *= ( n - i ) NEW_LINE ans /= ( i + 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def countDerangements ( n ) : NEW_LINE INDENT der = [ 0 for i in range ( n + 3 ) ] NEW_LINE der [ 0 ] = 1 NEW_LINE der [ 1 ] = 0 NEW_LINE der [ 2 ] = 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT der [ i ] = ( i - 1 ) * ( der [ i - 1 ] + der [ i - 2 ] ) NEW_LINE DEDENT return der [ n ] NEW_LINE DEDENT def countPermutations ( n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n - k , n + 1 ) : NEW_LINE INDENT ways = nCr ( n , i ) NEW_LINE ans += ways * countDerangements ( n - i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT n , k = 5 , 3 NEW_LINE print ( countPermutations ( n , k ) ) NEW_LINE