Count Derangements ( Permutation such that no element appears in its original position ) |  ; Base Case ; Variables for storing previous values ; using above recursive formula ; Return result for n ; Driver Code
/ * Function to count NEW_LINE derangements * / NEW_LINE def countDer ( n ) : NEW_LINE INDENT if n == 1 or n == 2 : NEW_LINE return n - 1 ; NEW_LINE a = 0 NEW_LINE b = 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT cur = ( i - 1 ) * ( a + b ) NEW_LINE a = b NEW_LINE b = cur NEW_LINE DEDENT return b NEW_LINE DEDENT n = 4 NEW_LINE print ( " Count ▁ of ▁ Dearrangements ▁ is ▁ " , countDer ( n ) ) NEW_LINE