Different Methods of Array Rotation in PythonIn this tutorial, we will learn how we can rotate the array using the Python program. We will write a function for rotation (arry[], E, K) which will be used for rotating arry[] of size K = 8 by E = 4 elements. We will get the following the array after rotating array by 4 elements: Methods for Array Rotation:In this session, we will discuss different methods users can use for rotation the array according to their requirements. Method 1: By using temp arrayIn this method, we will use the following approach: Step 1: We will store “E” elements in a temp array Temp[] = [1, 3, 5, 7] Step 2: we will shift the rest of the arry[] arry[] = [9, 11, 13, 15] Step 3: We will store the “E” elements arry[] = [9, 11, 13, 15, 1, 3, 5, 7] Example: Output: Array after Rotation by 4 elements is: [9, 11, 13, 15, 1, 3, 5, 7] In the above method: Method 2: By rotation elements one by oneIn this method, we will use the following approach: rotate_array1(arry[], E, K)
We have to store arry[0] for rotating elements by one in a temporary variable, “temp_1”. Then we will more arry[1] to arry[0], arry[2] to arry[1] and so on. At last, we will have temp_1 on arry[n-1]. Example: Output: The array after rotation: 1 3 5 7 9 11 13 15 In the above method: Method 3: By using a Juggling AlgorithmIn this method, we will be dividing the array into different sets instead of moving elements one by one. When the number of sets is equal to the greatest common divider of “K” and “E”, the code will mode the elements into the sets. If the greatest common divider is equal to 1, then the elements will move into one set only. Here, we will start with temp_1 = arry[0], and it will keep moving arry[J + E] to arry[J], and at last, it will store the temp_1 at the right place. Let’s see an example in which, K = 16 and E = 4. Greatest Common Divider (G_C_D) = 4 Steps –
After completion of this set, arry[] will be equal to [15, 12, 13, 14, 19, 16, 17, 18, 23, 20, 21, 22, 11, 23, 24, 25, 26]
Example: Output: The array after rotation: [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 11, 12, 13, 14] In the above method: Method 4: By using List SlicingIn this method, we will use list slicing for rotating the elements of an array. Example: Output: The List is: [11, 12, 13, 14, 15, 16, 17, 18] The rotated list is: [15, 16, 17, 18, 11, 12, 13, 14] If we want to rotate the array by more than its length, we can use the mod method. Suppose the array that we want to rotate by “E” is of “K” size and “E” is greater than “K”. In this case, we have to calculate (E%K) and then we can rotate by the output after mod calculation. ConclusionIn this article, we have discussed how we can use different methods for rotating the given array by using Python. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/courses/263411.html