forked from johnmee/codility
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex-2-1-cyclicrotation.py
54 lines (41 loc) · 1.31 KB
/
ex-2-1-cyclicrotation.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
import unittest
import random
ARRAY_RANGE = (-1000, 1000)
INT_RANGE = (0, 100)
def solution(A, K):
"""
Rotate the array A by k steps
:param A: an array of integers
:param K: number of times to shift right
:return: the rotated array
"""
# A is empty
if not len(A):
return A
# netK is the net number of shifts to apply (omits spinning round and round)
netK = (len(A) + K) % len(A)
if netK > 0:
head = A[len(A)-netK:]
tail = A[:-netK]
return head + tail
else:
return A
class TestCyclicRotation(unittest.TestCase):
def test_zero(self):
self.assertEqual(solution([6, 3, 8, 9, 7], 0), [6, 3, 8, 9, 7])
def test_one(self):
self.assertEqual(solution([6, 3, 8, 9, 7], 1), [7, 6, 3, 8, 9])
def test_example1(self):
self.assertEqual(solution([3, 8, 9, 7, 6], 3), [9, 7, 6, 3, 8])
def test_full(self):
self.assertEqual(solution([6, 3, 8, 9, 7], 5), [6, 3, 8, 9, 7])
def test_empty(self):
self.assertEqual(solution([], 5), [])
def test_random(self):
N = random.randint(*INT_RANGE)
K = random.randint(*INT_RANGE)
A = [random.randint(*ARRAY_RANGE) for i in xrange(0, N)]
print N, K, A
print solution(A, K)
if __name__ == '__main__':
unittest.main()