Python slice notation [:] - leetcode 189. Rotate Array

1. a[start:stop:step]

q = "12345"
w = q[0:2:1] # [0, 2)
print(f"w: {w}")
# w: 12

w = q[::-1] # if step is negative, reverse traverse
print(f"w's type: {type(w)} w: {w}")
# w's type: <class 'str'> w: 54321

w = q[::-2]
print(f"w: {w}") 
# w: 531

2. a = b[:] && b[:] = a

Example 1

a = b[:] means a = [ b[0], b[1], …, b[n-1] ]
It will create an new copy of b, so the id of a will change

b[:] = a means b[0], b[1], … b[n-1] = a
This won’t change the id of b.

a = [1, 2, 3]
print(f"a's id {id(a)}")
print(f"a = {a}")
# a's id 4364415176
# a = [1, 2, 3]


b = [4, 5, 6]
print(f"b's id {id(b)}")
print(f"b = {b}")
# b's id 4364415304
# b = [4, 5, 6]

b[:] = a
print(f"b's id {id(b)}")
print(f"b = {b}")
# b's id 4364415304
# b = [1, 2, 3]

b = a[:]
print(f"b's id {id(b)}")
print(f"b = {b}")
# b's id 4364415432
# b = [1, 2, 3]

Example 2

leetcode 189. Rotate Array
Given an array, rotate the array to the right by k steps, where k is non-negative.

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

def rotate(nums: List[int], k: int) -> None:
    n = len(nums)
    a = [0] * n
    for i in range(n):
        a[(i + k) % n] = nums[i]
        
    nums[:] = a # nums = a[:] is wrong !!!

nums = [1, 2, 3, 4, 5, 6]
rotate(nums, 2)
print(nums) # [5, 6, 1, 2, 3, 4]

But if in “rotate” function, we write nums = a[:]
nums is still [1, 2, 3, 4, 5, 6].

Although in the function scope, the id of “nums” has changed to a.
When it comes out of the function, in the global scope, the id of “nums” remains the same.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值