Count number of ways to arrange first N numbers | Python3 implementation of the approach ; Function to return the count of required arrangements ; Create a vector ; Store numbers from 1 to n ; To store the count of ways ; Initialize flag to true if first element is 1 else false ; Checking if the current permutation satisfies the given conditions ; If the current permutation is invalid then set the flag to false ; If valid arrangement ; Generate the all permutation ; Driver code
from itertools import permutations NEW_LINE def countWays ( n ) : NEW_LINE INDENT a = [ ] NEW_LINE i = 1 NEW_LINE while ( i <= n ) : NEW_LINE INDENT a . append ( i ) NEW_LINE i += 1 NEW_LINE DEDENT ways = 0 NEW_LINE INDENT flag = 1 if ( per [ 0 ] == 1 ) else 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( abs ( per [ i ] - per [ i - 1 ] ) > 2 ) : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT ways += 1 NEW_LINE DEDENT DEDENT return ways NEW_LINE for per in list ( permutations ( a ) ) : NEW_LINE DEDENT n = 6 NEW_LINE print ( countWays ( n ) ) NEW_LINE