MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / rotate_array

Function rotate_array

data_structures/arrays/rotate_array.py:1–67  ·  view source on GitHub ↗

Rotates a list to the right by steps positions. Parameters: arr (List[int]): The list of integers to rotate. steps (int): Number of positions to rotate. Can be negative for left rotation. Returns: List[int]: Rotated list. Examples: >>> rotate_array([1, 2, 3, 4, 5]

(arr: list[int], steps: int)

Source from the content-addressed store, hash-verified

1def rotate_array(arr: list[int], steps: int) -> list[int]:
2 """
3 Rotates a list to the right by steps positions.
4
5 Parameters:
6 arr (List[int]): The list of integers to rotate.
7 steps (int): Number of positions to rotate. Can be negative for left rotation.
8
9 Returns:
10 List[int]: Rotated list.
11
12 Examples:
13 >>> rotate_array([1, 2, 3, 4, 5], 2)
14 [4, 5, 1, 2, 3]
15 >>> rotate_array([1, 2, 3, 4, 5], -2)
16 [3, 4, 5, 1, 2]
17 >>> rotate_array([1, 2, 3, 4, 5], 7)
18 [4, 5, 1, 2, 3]
19 >>> rotate_array([], 3)
20 []
21 """
22
23 n = len(arr)
24 if n == 0:
25 return arr
26
27 steps = steps % n
28
29 if steps < 0:
30 steps += n
31
32 def reverse(start: int, end: int) -> None:
33 """
34 Reverses a portion of the list in place from index start to end.
35
36 Parameters:
37 start (int): Starting index of the portion to reverse.
38 end (int): Ending index of the portion to reverse.
39
40 Returns:
41 None
42
43 Examples:
44 >>> example = [1, 2, 3, 4, 5]
45 >>> def reverse_test(arr, start, end):
46 ... while start < end:
47 ... arr[start], arr[end] = arr[end], arr[start]
48 ... start += 1
49 ... end -= 1
50 >>> reverse_test(example, 0, 2)
51 >>> example
52 [3, 2, 1, 4, 5]
53 >>> reverse_test(example, 2, 4)
54 >>> example
55 [3, 2, 5, 4, 1]
56 """
57
58 while start < end:
59 arr[start], arr[end] = arr[end], arr[start]
60 start += 1

Callers 1

rotate_array.pyFile · 0.85

Calls 1

reverseFunction · 0.85

Tested by

no test coverage detected