How to fill two instances of all numbers from 1 to n in a specific way in Python
In this tutorial, we are going to learn how we can fill two instances of all numbers from 1 to n in a specific way in Python.
A number is given in this problem which is said to be n. An array is to be created with the size 2n.
the array must contain two instances of every number from one to that given number i.e. n.
The elements between those two instances must b equal to that number.
Input: n = 2 Output: Not Possible Input: n = 11 Output: 11 6 10 2 9 3 2 8 6 3 7 5 11 10 9 4 8 5 7 1 4 1 Input: n = 5 Output: Not Possible
One of the solutions to this is backtracking.
In this, we place two instances of n at a place and then go for recurrence for n-1.
If recurrence is successful then we get true else we go trying to place n at different locations to obtain
the desired result.
# To fill two instances of all numbers def fill(result, current, m): #If current number becomes 0 then all numbers are filled if current == 0: return True # Try placing two instances of 'curr' at all # possible locations till solution is found for i in range(2 * m - current - 1): if result[i] == 0 and result[i + current + 1] == 0: # Place two instances of 'curr' result[i] = result[i + current + 1] = current #Check the above if fill(result, current - 1, m): return True # If solution is not possible, # then backtrack result[i] = 0 result[i + current + 1] = 0 return False def fillin(m): # This function prints the result # Create an array of size 2n result = [0] * (2 * m) # Print not possible if solution is not possible if fill(result, m, m): for i in range(2 * m): print(result[i], end=' ') print() else: print("Not Possible") if __name__ == '__main__': fillin(11)
Output
Leave a Reply