Slicingslicing-rotate-right
LessonΒ·difficulty 2/5Β·~12 min
Slicing: rotate right by k
Slicing: rotate right by k
Slicing carves out part of a list with list[start:stop]. Two slices can
be glued back together with +:
python
nums = [1, 2, 3, 4, 5]
nums[3:] # [4, 5] β from index 3 to the end
nums[:3] # [1, 2, 3] β up to (not including) index 3
nums[3:] + nums[:3] # [4, 5, 1, 2, 3]
Rotating a list right by k means the last k items wrap around to the
front. Note the slice point is len(nums) - k.
Your task
Write rotate(nums, k) that returns a new list rotated right by k.
Handle a k larger than the length (use k % len) and the empty list.
python
rotate([1, 2, 3, 4, 5], 2) # [4, 5, 1, 2, 3]
rotate([1, 2, 3], 4) # [3, 1, 2] β 4 % 3 == 1
rotate([], 3) # []
Hint: compute k = k % len(nums), then return nums[-k:] + nums[:-k]
(and guard the empty list first, since % 0 would fail).
Tests
- rotate by 2
- k larger than len
- empty list
- k is zero
- k equals len (hidden)
- single element (hidden)
Stuck? Ask for a spark
warming up
Loading editorβ¦
$ Console output will appear here.