Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #7014

Re: Lambda question

Path csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!.POSTED!not-for-mail
From Mel <mwilson@the-wire.com>
Newsgroups comp.lang.python
Subject Re: Lambda question
Followup-To comp.lang.python
Date Sat, 04 Jun 2011 14:21:51 -0400
Organization Aioe.org NNTP Server
Lines 53
Message-ID <isdt3t$h2c$1@speranza.aioe.org> (permalink)
References <mailman.2454.1307209587.9059.python-list@python.org>
Reply-To mwilson@the-wire.com
NNTP-Posting-Host OYwD5Ys/jc+mN+CJF0yltg.user.speranza.aioe.org
Mime-Version 1.0
Content-Type text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding 7Bit
X-Complaints-To abuse@aioe.org
User-Agent KNode/4.4.8
X-Notice Filtered by postfilter v. 0.8.2
Xref x330-a1.tempe.blueboxinc.net comp.lang.python:7014

Followups directed to: comp.lang.python

Show key headers only | View raw


jyoung79@kc.rr.com wrote:

> I was surfing around looking for a way to split a list into equal
> sections.  I came upon this algorithm:
>  
>>>> f = lambda x, n, acc=[]: f(x[n:], n, acc+[(x[:n])]) if x else acc
>>>> f("Hallo Welt", 3)
> ['Hal', 'lo ', 'Wel', 't']
>  
> http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-
evenly-s
> ized-chunks-in-python/312644
>  
> It doesn't work with a huge list, but looks like it could be handy in
> certain
> circumstances.  I'm trying to understand this code, but am totally lost. 
> I know a little bit about lambda, as well as the ternary operator, but how
> does this part work:
>  
>>>> f('dude'[3:], 3, []+[('dude'[:3])])
> ['dud', 'e']
>  
> Is that some sort of function call, or something else?  I'm guessing it
> works recursively?

Yeah, recursive.

f('dude', 3) 

evaluates to

f('e', 3, []+['dud']) if 'dude' else []

which evaluates to

f('', 3, []+['dud']+['e']) if 'e' else []+['dud']

which evaluates to

[]+['dud']+['e']

because the if...else finally takes the second branch since the x value is 
now an empty string.  

I've left the list additions undone .. tracing the actual data objects would 
show plain lists.  One of the disadvantages of lambdas is that you can't 
stick trace printouts into them to clarify what's happening.  Rewriting the 
thing as a plain def function would be instructive.

	Mel.


Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Lambda question <jyoung79@kc.rr.com> - 2011-06-04 17:46 +0000
  Re: Lambda question Mel <mwilson@the-wire.com> - 2011-06-04 14:21 -0400
  Re: Lambda question Alain Ketterlin <alain@dpt-info.u-strasbg.fr> - 2011-06-05 11:31 +0200
    Re: Lambda question Terry Reedy <tjreedy@udel.edu> - 2011-06-05 14:33 -0400
      Re: Lambda question rusi <rustompmody@gmail.com> - 2011-06-06 10:29 -0700
        Re: Lambda question Terry Reedy <tjreedy@udel.edu> - 2011-06-06 21:56 -0400

csiph-web