How do I reverse a sublist in a list in place?

前端 未结 12 2586
-上瘾入骨i
-上瘾入骨i 2021-02-20 01:24

I\'m supposed to create a function, which input is a list and two numbers, the function reverses the sublist which its place is indicated by the two numbers. for example this is

12条回答
  •  -上瘾入骨i
    2021-02-20 02:17

    Two methods in-place and constant memory:

    def reverse_swap(arr, start=None, end=None):
        """
        Swap two edge pointers until meeting in the center.
        """
    
        if start is None:
            start = 0
        if end is None:
            end = len(arr)
    
        i = start
        j = end - 1
        while i < j:
            arr[i], arr[j] = arr[j], arr[i]
            i += 1
            j -= 1
    
    def reverse_slice(arr, start=None, end=None):
        """
        Use python slice assignment but use a generator on the right-hand-side
        instead of slice notation to prevent allocating another list.
        """
    
        if start is None:
            start = 0
        if end is None:
            end = len(arr)
    
        arr[start:end] = (arr[i] for i in range(end - 1, start - 1, -1))
    

提交回复
热议问题