需要备用Python列表反向解决方案 [英] Alternate Python List Reverse Solution Needed

查看:58
本文介绍了需要备用Python列表反向解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天进行了面试.在此期间,我被要求写下一个将反转列表的算法.首先,我使用reversed()方法提供了答案:

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:

    x = [1,2,3,4,5]
    y = reversed(x)
    for i in y:
        print i

进行面试的高级开发人员问我是否知道另一种方法,然后我用切片方法写下了另一种已知方法:

The senior developer conducting the interview asked me if I know another way, upon which I wrote down the other known method with slicing:

   x = [1,2,3,4,5]
   y = x[::-1]

不幸的是,他也对这种解决方案不满意,并请我考虑另一种解决方案.几分钟后,我说我无法提出更好的解决方案.他说,这对于他们的标准来说还不够.

Unfortunately he was unhappy with this solution as well and asked me to think of another one. After few minutes I said I could not come up with a better one. He said that this was not good enough for their standards.

我对他的观点完全满意,对我的代码进行更多的练习也没有问题.我的问题是,如果有的话,什么是我不知道的更好的解决方案.可能还有其他的程序员"方式……只有其他想到的是递归,但是我只有在面试已经完成之后才想到它. 谢谢.

I am perfectly fine with his opinion and have no problem practicing more on my code. My question is, what is a better solution that I am not aware of, if there is one. Could there be some other more 'programmer' way...Only other thing that comes to mind is recursion, however I thought of it only after the interview was already done. Thanks.

推荐答案

在python方面,您的答案都是不错的,所以面试官一定一直在要求您实现自己的方法:

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

使用递归:

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

或者列表组合和范围从l -1的长度开始,然后反向:

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)])

使用itertools.count:

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)

或使用地图:

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]

在地图上没有列表调用,我们将获得一个地图对象,可以在python3中进行迭代,您可以使用

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

这篇关于需要备用Python列表反向解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆