Alternate Python List Reverse Solution Needed

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

    How about something like that:

    x = [1, 2, 3, 4, 5]
    
    for i in xrange(len(x) / 2):
        x[i], x[-i - 1] = x[-i - 1], x[i]
    
    print(x)
    

    The idea is to swap array elements from opposite directions

提交回复
热议问题