Recursively decrement a list by 1

2020-08-11 04:23发布

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.

7条回答
兄弟一词,经得起流年.
2楼-- · 2020-08-11 05:05

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

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.

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.

查看更多
登录 后发表回答