如何在 Python 中仅使用递归返回列表的奇数?
我不想使用 while 或 for 循环,只想使用递归返回给定列表中的奇数。谢谢!
I do not want to use while or for loops, just want to use recursion to return the odd numbers in a given list. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
不需要额外的变量或参数。
No extra variables or parameters needed.
这个版本要快得多,因为它避免了复制 L
这个版本只使用 O(log n) 堆栈空间
This version is much faster as it avoids making copies of L
This one only uses O(log n) stack space
时得到的测试输出
这是运行[7, 5, 3, 1]
Here's a test output of what I get when I run this
[7, 5, 3, 1]
考虑到 python 中默认的堆栈深度限制为 1000,我真的不会为此使用递归。我知道上面有很多递归实现,所以这里有一个以 python 方式实现的非递归实现
:如果你真的必须使用递归,这是我的尝试。这与乔什·马修斯的版本非常相似。
Considering the default stack depth limit of 1000 in python, I would really not use recursion for this. I know there are a lot of recursive implementations above so here's a non-recursive one that is doing it the python way:
And for the sake of completeness; if you really really must use recursion here's my go at it. This is very similar to the version by Josh Matthews.
这是另一种方法,它返回奇数列表,而不是修改传入的列表。与
GWW
提供的非常相似,但我想为了完整性而添加它。输出是:
Here's another way of doing it which returns the list of odd numbers rather than modifying the list passed in. Very similar to that provided by
GWW
but I thought I'd add it for completeness.Output is:
由于这是一个聚会,我只是想提出一个好的、合理的、真正的程序员TM解决方案。它是用 emacs 编写的,灵感来自 gnibbler 的答案。与他一样,它使用
&1
而不是% 2
(如果 1 已经存在,则将 2 添加到co_consts
中是纯粹的颓废)并使用它仅当第一个元素奇数时才获取第一个元素的巧妙技巧,但减少了一些周期,节省了大约 5% 的时间(在我的机器上,在 linux2 内核上运行用 GCC 4.4.3 编译的 2.6.5)。Since it's a party, I just thought I'd chime in with a nice, sensible, Real ProgrammerTM solution. It's written in emacs and inspired by gnibbler's answer. Like his, it uses
&1
instead of% 2
(adding 2 intoco_consts
is pure decadence if 1 is already there) and uses that nifty trick for getting the first element only if it's odd, but shaves some cycles off for a time savings of around 5% (on my machine, running 2.6.5 compiled with GCC 4.4.3 on a linux2 kernel).这避免了列表复制开销,但代价是向后获得答案并大幅增加丑陋因素:
This one avoids the list copying overhead, at the cost of getting the answer backwards and a big increase in the ugliness factor:
好吧,因为我们都在做出贡献:
well since we're all contributing:
好吧,还有很多其他答案,但我认为我的答案是最干净的:
有趣的练习,但只是重申一下,在实践中永远不要递归地执行此操作。
Well, there are a bunch of other answers but I think mine's the cleanest:
Fun exercise but just to reiterate, don't ever do this recursively in practice.