Alternate Python List Reverse Solution Needed

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

    Both your answers are good in terms of python so the interviewer must have been asking you to implement your own method:

    Using recursion:

    def recur_rev(l):
        return recur_rev(l[1:]) + l[:1] if l else l
    

    Or a list comp and range starting at the length of l -1 and going in reverse:

    l = list(range(100))
    
    print([l[ind] for ind in range(len(l)-1,-1,-1)])
    

    Using itertools.count:

    from itertools import count
    cn = count(len(l) -1, -1)
    
    print([l[next(cn)] for ele in l])
    

    For efficiency use a generator expression:

    rev  = (l[next(cn)] for ele in l)
    
    for ele in rev:
        print(ele)
    

    Or using map:

    print(list(map(l.__getitem__,range(len(l)-1,-1,-1)))) # list needed for python3
    
    [99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    

    without the list call on map we will get a map object we can iterate over in python3, you can use itertools.imap in python2 to achieve a similar result

    0 讨论(0)
提交回复
热议问题