递归地将列表递减 1 [英] Recursively decrement a list by 1
问题描述
非常快速和简单的家庭作业问题.我运行正常,但我认为有更好的
方法来做到这一点.一种更 Pythonic 的方式.
这是我的代码,以递归方式将列表的每个元素递减 1.
Very quick and easy homework question. I have it running ok but I think there's a better
way to do it. A more Pythonic way.
Here's my code to recursively decrement each element of a list by 1.
l = range(30)
def recurseDecrMap(l, x = []):
if len(l) == 0:
return []
else:
x.append(l[0] -1)
recurseDecrMap(l[1:], x)
return x
所以感谢您的任何意见.我正在努力学习做更好的递归.获取困难
它的诀窍.
So thanks for any input. I'm trying to learn to do better recursion. Having trouble getting
the knack of it.
推荐答案
你只能使用一个参数,在我看来它更简单:
You can use only one argument, in my opinion it is simpler:
def recurseDecrMap(l):
if not l:
return []
else:
return [l[0]-1] + recurseDecrMap(l[1:])
但正如@jamylak 指出的那样,这个算法的复杂度是 O(N^2),因为 l[1:]
创建了一个新列表,其中引用了列表.
But as @jamylak pointed out, the complexity of this algorithm is O(N^2), since l[1:]
creates a new list with references to the rest of the items in the list.
如果您需要效率,我建议您使用列表推导式 (Haidro 的回答),但我认为如果您仅出于学习目的而想要它,这不是优先事项.
If you need efficiency, I'd recommend you using list comprehensions (Haidro's answer), but I suppose it is not a priority if you want it only for learning purposes.
这篇关于递归地将列表递减 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!