@Phrancis/

Array Rotations

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/bin/python3

def rotate_right(array:list, rotate_by:int = 1) -> list:
    '''
    Default behavior: 
        Given input [1,2,3] return [3,1,2]
    Supplying a rotate_by value other than 1 will increase the number
    of positions the values are moved towards the right by.
    '''
    if rotate_by < 0:
        return rotate_left(array, - rotate_by)
    array_length = len(array)
    rotate_by = minimize_rotations(array_length, rotate_by)
    return [array[i - rotate_by] for i in range(array_length)]

def rotate_left(array:list, rotate_by:int = 1) -> list:
    '''
    Default behavior: 
        Given input [1,2,3] return [2,3,1]
    Supplying a rotate_by value other than 1 will increase the number
    of positions the values are moved towards the left by.
    '''
    if rotate_by < 0:
        return rotate_right(array, - rotate_by)
    array_length = len(array)
    rotate_by = minimize_rotations(array_length, rotate_by)
    rotated = []
    for i in range(array_length):
        val_index = i + rotate_by
        if val_index >= array_length:
            val_index -= array_length
        rotated.append(array[val_index])
    return rotated

def minimize_rotations(array_length:int, rotate_by:int) -> int:
    while rotate_by >= array_length:
        rotate_by -= array_length 
    return rotate_by
    
def main():
    # Testing code
    arr = [1,2,3,4,5,6,7,8]
    rotate_by = 1
    print('Input array:', arr)
    print('Rotate by:', rotate_by)
    arr_L = arr_R = arr
    print('Rotate left:')
    for _ in range(len(arr)):
        arr_L = rotate_left(arr_L, rotate_by)
        print(arr_L)
    print('Rotate right:')
    for _ in range(len(arr)):
        arr_R = rotate_right(arr_R, rotate_by)
        print(arr_R)
    
main()