Alternate Python List Reverse Solution Needed

后端 未结 7 756
清酒与你
清酒与你 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:37

    I like this way:

    def reverse(arr):
        for i in range(len(arr) / 2): 
            arr[-i-1], arr[i] = arr[i], arr[-i-1]
    

    Basically iterating through the first half of the array and swapping i and len(i)-i-1.

提交回复
热议问题