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

前端 未结 12 2605
-上瘾入骨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条回答
  •  日久生厌
    2021-02-20 02:09

    I have two ways for in-place reversal, the simple way is to loop through the list half-way, swapping the elements with the respective mirror-elements. By mirror-element I mean (first, last), (2nd, 2nd-last), (3rd, 3rd-last), etc.

    def reverse_list(A):
        for i in range(len(A) // 2): # half-way
            A[i], A[len(A) - i - 1] = A[len(A) - i - 1], A[i] #swap
        return A
    

    The other way is similar to the above but using recursion as opposed to a "loop":

    def reverse_list(A):
        def rev(A, start, stop):
            A[start], A[stop] = A[stop], A[start] # swap
            if stop - start > 1: # until halfway
                rev(A, start + 1, stop - 1)
            return A
    
        return rev(A, 0, len(A) - 1)
    

提交回复
热议问题