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

前端 未结 12 2577
-上瘾入骨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:06

    I've conducted a tiny experiment and it seems that any assignment to list slice causes memory allocation:

    import resource
    resource.setrlimit(resource.RLIMIT_AS, (64 * 1024, 64 * 1024))
    
    try:
        # Python 2
        zrange = xrange
        arr_size = 3 * 1024
    except NameError:
        # Python 3
        zrange = range
        arr_size = 4 * 1024
    
    arr = list(zrange(arr_size))
    
    # We could allocate additional 100 integers, so there should be enough free memory
    # to allocate a couple of variables for indexes in the statement below
    #   additional_memory = list(zrange(100))
    
    # MemoryError is raised here
    arr[:] = zrange(arr_size)
    

    So you have to use for loop to reverse a sublist in place.

    PS: If you want to repeat this test, you should ensure that setrlimit RLIMIT_AS works fine on your platform. Also arr_size may vary for different python implementations.

提交回复
热议问题