0

how to create a function that copies every value in the original list to a new list where the position of every value in the new list is shifted to the left by the specified shift amount

e.g. [2,3,4,5] woule become [4,5,2,3]

How can I create this function WITHOUT using any builtin functions?

1 Answers1

0

Solution

a = [2, 3, 4, 5]


def shift_left(arr: list, amount: int) -> list:
    amount %= len(arr)  # (1)
    return arr[amount:] + arr[:amount]  # (2)


for i in range(len(a) * -2, len(a) * 2):
    print(i, shift_left(a, i))

output:

-8 [2, 3, 4, 5]
-7 [3, 4, 5, 2]
-6 [4, 5, 2, 3]
-5 [5, 2, 3, 4]
-4 [2, 3, 4, 5]
-3 [3, 4, 5, 2]
-2 [4, 5, 2, 3]
-1 [5, 2, 3, 4]
0 [2, 3, 4, 5]
1 [3, 4, 5, 2]
2 [4, 5, 2, 3]
3 [5, 2, 3, 4]
4 [2, 3, 4, 5]
5 [3, 4, 5, 2]
6 [4, 5, 2, 3]
7 [5, 2, 3, 4]

Explanation

  1. amount %= len(arr): normalize the amount within length of the array.
  2. arr[amount:] + arr[:amount]: slice the array into two parts and concatenate it.
Boseong Choi
  • 2,566
  • 9
  • 22