0

I have a list which is a list of list (of list ...)

[ [], [ [] ] ]

Can I make a lambda function that returns the sum of the length of the lists at the bottom of this tree?

The one up here will return 0 because contains only empty lists. but this one:

[ ['foo'], [ [ [], [] ] ] ]

will return 3 which is the length of 'foo'. This one:

[ 'aa', [], [ ['ab'], [] ] ]

will return 4.

Thanks!

Matteo
  • 65
  • 1
  • 6
  • 3
    Why a lambda specifically? (I think the answer to the question as stated is "no" because Python lambdas don't have names, but it's a trivial exercise in recursion with a regular `def`.) – zwol Mar 06 '14 at 19:49
  • What have you tried so far? Perhaps we might be able to spot the error in logic. – wheaties Mar 06 '14 at 19:49
  • that's not returning the length of the lists, but the sum of the length of non-empty elements... is that what you want? – isedev Mar 06 '14 at 19:49
  • write a `flatten` function, however you'd like, then just do `sum(len(x) for x in flatten(li))`. Forcing the use of `lambda`s is not going to make the solution better in any way. – roippi Mar 06 '14 at 19:53
  • 1
    See [Can a lambda function call itself recursively in Python?](http://stackoverflow.com/q/481692/222914) – Janne Karila Mar 06 '14 at 19:53
  • As @JanneKarila stated, `lambda f, *a: f (f, *a)` is your recursive friend. – Hyperboreus Mar 06 '14 at 19:54
  • Y-Combinators are a pain in the @$$ to write ... imho – Joran Beasley Mar 06 '14 at 20:00
  • 1
    @JoranBeasley But it is lambda calculus at its finest... Looks impressive, is illegible and completely uncalled for. – Hyperboreus Mar 06 '14 at 20:04

1 Answers1

1
recur = lambda l:len(l) if not isinstance(l,(tuple,list)) else sum(map(recur,l))

I think would work

or even cooler (self refering lambda :))

def myself (*args, **kw):
    caller_frame = currentframe(1)
    code = caller_frame.f_code
    return  FunctionType(code, caller_frame.f_globals)(*args,**kw)

print (lambda l:len(l) if not isinstance(l,(tuple,list)) else sum(map(myself,l)))(some_list)

or hyperboreus solution

lambda a:(lambda f, a: f(f, a))(lambda f, a:len(a) if not isinstance(a,(tuple,list)) else sum(f(f,e) for e in a), a)

which is whats known as a Y-Combinator ... which are nightmares to tell whats going on but they somehow work :P

Joran Beasley
  • 93,863
  • 11
  • 131
  • 160
  • 1
    Just to keep the code golf going: Same thing with recursive, anonymous lamda and no stack inspection: `lambda a:(lambda f, a: f(f, a))(lambda f, a:len(a) if not isinstance(a,(tuple,list)) else sum(f(f,e) for e in a), a)`. For Python3 at least. – Hyperboreus Mar 06 '14 at 20:00
  • Thank you very much! I thought hardly before and it this is ingenious for me.. But how can I make that anonymous so I can call it in a while: while lambda: .......... : ?? You can read in my mind ;) – Matteo Mar 06 '14 at 20:05