Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively decrement a list by 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.

like image 943
Loubot Avatar asked Apr 27 '13 23:04

Loubot


1 Answers

Here's the worst way - using Fixed Point Combinator:

Y = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda arg: f(f)(arg)))
recurseDecrMap = Y(lambda f: lambda l: [l[0]-1] + f(l[1:]) if l else [])
like image 149
Elazar Avatar answered Sep 20 '22 13:09

Elazar