26 lines
674 B
Python
26 lines
674 B
Python
def rotate(nums, k):
|
|
"""
|
|
Rotate the elements of the list nums to the right by k positions.
|
|
|
|
Args:
|
|
nums (List[int]): List of integers to be rotated.
|
|
k (int): Number of positions to rotate the elements.
|
|
|
|
Returns:
|
|
None. Modifies nums in-place.
|
|
|
|
Example:
|
|
>>> rotate([1,2,3,4,5,6,7], 3)
|
|
[5, 6, 7, 1, 2, 3, 4]
|
|
"""
|
|
k %= len(nums) # Adjust k if it's larger than the length of the list
|
|
|
|
# Use slicing to shift the elements to the right
|
|
nums = nums[-k:] + nums[:-k]
|
|
|
|
print(nums) # Print the rotated list (optional)
|
|
|
|
# Example usages
|
|
rotate([1,2,3,4,5,6,7], 3)
|
|
rotate([-1,-100,3,99], 2)
|
|
rotate([1,2], 3) |