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!

8
  • 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.) Commented Mar 6, 2014 at 19:49
  • What have you tried so far? Perhaps we might be able to spot the error in logic. Commented Mar 6, 2014 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? Commented Mar 6, 2014 at 19:49
  • 1
    See Can a lambda function call itself recursively in Python? Commented Mar 6, 2014 at 19:53
  • 1
    @JoranBeasley But it is lambda calculus at its finest... Looks impressive, is illegible and completely uncalled for. Commented Mar 6, 2014 at 20:04

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.