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:  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.

你可能感兴趣的:(python,算法)