Skip to content

Instantly share code, notes, and snippets.

@kleutzinger
Created March 31, 2021 08:33
Show Gist options
  • Save kleutzinger/f18d9abaeb3a2232fc9c64ace3c886f3 to your computer and use it in GitHub Desktop.
Save kleutzinger/f18d9abaeb3a2232fc9c64ace3c886f3 to your computer and use it in GitHub Desktop.
def rotate_left_1(A):
"rotate in place once to the left (as if k = 1)"
for i in range(len(A) - 1):
A[i], A[i + 1] = A[i + 1], A[i]
def rotate_right_1(A):
"rotate in place once to the right (as if k = -1)"
for i in range(len(A) - 1):
A[i], A[i - 1] = A[i - 1], A[i]
def rotate(A, k):
"rotate in place k times to the left"
k = k % len(A)
for _ in range(k):
if k > 0:
rotate_left_1(A)
else:
rotate_right_1(A)
if __name__ == "__main__":
# example table of rotations
print("list, k")
for i in [0, 1, 2, 3, 4, -1, -2, -3, -4, 400]:
A = list("ABCD")
rotate(A, i)
print("".join(A), i)
"""
list, k
ABCD 0
BCDA 1
CDAB 2
DABC 3
ABCD 4
DABC -1
CDAB -2
BCDA -3
ABCD -4
ABCD 400
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment