【每日一题0718】旋转列表

:woman_mage:给你一个数字列表nums,请编写一个函数,将列表中的元素向右移动 k 个位置,然后返回移动后的列表。其中 k 是非负数。

示例:
输入: nums = [1,2,3,4,5,6,7], k = 3
返回: [5,6,7,1,2,3,4]

解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]

题目难度:简单
题目来源:力扣LeetCode

def rotate(nums, k):
    pass

assert rotate([1,2,3,4,5,6,7],3) == [5,6,7,1,2,3,4]
assert rotate([-1,-100,3,99], 2)== [3,99,-1,-100]
def rotate(nums, k):
    index = len(nums) - k
    result = nums[index:]
    result.extend(nums[:index])
    return result


assert rotate([1, 2, 3, 4, 5, 6, 7], 3) == [5, 6, 7, 1, 2, 3, 4]
assert rotate([-1, -100, 3, 99], 2) == [3, 99, -1, -100]
def rotate(nums, k):
    ls = nums[len(nums) - k::]
    ls2 = nums[:len(nums) - k]
    ls3 = ls + ls2
    return ls3

assert rotate([1,2,3,4,5,6,7],3) == [5,6,7,1,2,3,4]
assert rotate([-1,-100,3,99], 2) == [3,99,-1,-100]
def rotate(nums, k):
    length = len(nums)
    return nums[length - k:length] + nums[:length - k]
  

assert rotate([1, 2, 3, 4, 5, 6, 7], 3) == [5, 6, 7, 1, 2, 3, 4]
assert rotate([-1, -100, 3, 99], 2) == [3, 99, -1, -100]
def rotate(nums, k):
    j = len(nums)-k
    return nums[j:]+nums[:j]

assert rotate([1, 2, 3, 4, 5, 6, 7], 3) == [5, 6, 7, 1, 2, 3, 4]
assert rotate([-1, -100, 3, 99], 2) == [3, 99, -1, -100]
def rotate(nums, k):
    """ 0718 旋转列表 """
    # nums = [1, 2, 3, 4, 5, 6, 7]
    # k = 5
    return nums[-k:]+nums[:-k]

def  rotate(nums:list,k:int):
    res=[]
    for i in range(len(nums)):
        if i<k:
            res.append(nums[-k+i])
        else:
            res.append(nums[i-k])
    return res
def rotate(nums, k):
    nums = nums[-k:] + nums[:len(nums)-k]
    return nums

@cold_watermelon @zhanfengzh_9391 @lifq1984 @765120214 @sunyanfen @fwj
不好意思,刚发现,之前assert 断言第二条的函数名字粘错了。。。大家如果发现错误,帮忙提醒我纠正哈 :grin: