Javatpoint Logo
Javatpoint Logo

Smallest Derangement of Sequence using Python

A derangement of an arranged grouping is a stage of its components in combinatorial science wherein none of the components show up in their underlying positions. On account of a succession like [1, 2, 3, 4], for example, an insanity of this grouping would be [2, 1, 4, 3] since no component is in its underlying position.

Uses of disturbances in math, software engineering, and cryptography are captivating. Finding the most reduced insanity in a given grouping is a common issue. Here, we'll take a gander at how to utilize Python to decide a succession's littlest insanity.



2 1 4 3 6 5 8 7


In the primary part of the code, we outline a function generate_derangement that takes an integer N as enter. This function is answerable for producing the smallest derangement of a chain of integers from 1 to N.

We start via initializing an empty list P of length (N + 1) to represent the sequence. We use a loop to populate P with integers from 1 to N, correctly creating a sequence of integers.

Next, we initialize some other empty listing D of the identical length as P to represent the derangement. The derangement may be constructed based on the sequence P.

We then enter a loop that iterates from 1 to N with a step of 2. This loop is used to assemble the derangement through swapping adjoining factors in P to make sure that no detail appears in its original function.

Inside the loop,the two cases were present

  • If i is equal to N, it means that we're processing the remaining element. In this case, we switch the final two factors of P to ensure that the final element isn't in its unique role. We do that by assigning the values of P[N - 1] to D[N] and P[N] to D[N - 1].
  • If i isn't equal to N, we swap the current detail at index i with the following detail at index i + 1. This guarantees that each one element except the last one are not in their original positions.

Finally, we iterate through the D listing and print the elements of the derangement, separated by means of areas.

The if __name__ == '__main__': block on the end of the code is used to execute the generate_derangement characteristic while the script is administered as the main program. In this case, it generates the smallest derangement for N = 8 and prints it.

In order to move the least significant elements (minimum index locations) into more significant positions, we shall use a min-heap. We shall carry out this algorithm while preserving the derangement property.

We will use the supplied sorted_sequence as the parameter when calling the function. We will obtain the smallest derangement sequence list, which does not share any elements with the sorted_sequence list, as our output.



[2, 1, 4, 3, 6, 7, 5]

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA