Alternate Python List Reverse Solution Needed

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

    One simple algorithm that could be easily ported to other languages would be:

    x = [1,2,3,4,5]
    y = []
    for i in len(x):
      y.append(x[len(x) - 1 - i])
    

    Or using an iterator. This could be easily ported to be used with a chained list where you don't know the length:

    x = [1,2,3,4,5]
    y = []
    x_iterator = iter(x)
    try:
      while (1):
        y.insert(0, x_iterator.next())
    except:
      print y
    

    Or a more pythonic version with insert:

    x = [1,2,3,4,5]
    y = []
    for elem in x:
      y.insert(0, elem)
    

提交回复
热议问题