Alternate Python List Reverse Solution Needed

后端 未结 7 771
清酒与你
清酒与你 2021-01-22 09:54

I had a job interview today. During it I was asked to write down an algorithm that will reverse a list. First I offered the answer using the reversed() method:

          


        
7条回答
  •  感动是毒
    2021-01-22 10:45

    I guess your interviewer wanted to hear something like this:

    A straightforward way to revert a list is to find out its length, then iterate from len-1 downto 0 and append the i-th element to the result. This approach works fine with real lists, but how can we revert a generator, i.e. something whose length is not known and cannot be found? (Good pythonistas use generators and yields instead of lists and returns).

    Here's where we need a data structure known as "stack". A stack is like, well, a stack of things, like plates, put on the top of each other.

    Whatever you put last comes out first, whatever was put first comes out last. So, our strategy will be like this:

    • while there are items, put each item onto the stack
    • while the stack is not empty, pop items off the stack and return them

    Stacks can be programmed in python using lists, where .append puts an item on the top of the stack, and .pop removes the last thing off the stack:

    def reverse(it):
        stack = []
        for item in it:
            stack.append(item)
        while stack:
            yield stack.pop()
    

    Of course, Python already has a built-in stack, and it's the stack of call frames. We can use that instead of the simulated one above, which leads us to the following recursive solution:

    def reverse(it):
        head = next(it)
        for item in reverse(it):
            yield item
        yield head
    

    in python3, this is even more elegant:

    def reverse(it):
        head = next(it)
        yield from reverse(it)
        yield head
    

    Again, this works with arbitrary iterables, whose length is unknown at the call time.

提交回复
热议问题