Lambda question

Chris Angelico rosuav at gmail.com
Sat Jun 4 14:09:07 EDT 2011


On Sun, Jun 5, 2011 at 3:46 AM,  <jyoung79 at kc.rr.com> wrote:
> 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']

First, the easy bit. 'dude'[3:] is a slice operation on the string;
same with 'dude'[:3]. Imagine the gaps between the letters as being
numbered from zero:

| d | u | d | e |
0  1  2  3  4

'dude'[3:] means "take the string 'dude', start at position 3, and go
to the end of the string" - so that's just the letter "e". Similarly,
'dude'[:3] means "take the string 'dude', start at the beginning, and
go to position 3" - so that's "dud".

Here's a version of that function, redone in a slightly less compact form:

def strsplit(string,n,acc=[]):
	if string:
		return strsplit(string[n:],n,acc+[string[:n]])
	else:
		return acc

Yes, it's recursive. In each iteration, until the string is empty, it
takes the first n characters and puts them in the accumulator list,
and then trims those n off and leaves them in the string. Here's a
non-recursive version:

def strsplit(string,n):
	acc=[]
	while string:
		acc.append(string[:n])
		string=string[n:]
	return acc

This might make it a bit clearer what it does. The accumulator
collects ("accumulates") short strings, the string gets progressively
snipped, and once the string is empty, it evaluates as False and
terminates the loop.

Python doesn't seem to have an inbuilt function to divide strings in
this way. At least, I can't find it (except the special case where n
is 1, which is simply 'list(string)'). Pike allows you to use the
division operator: "Hello, world!"/3 is an array of 3-character
strings. If there's anything in Python to do the same, I'm sure
someone else will point it out.

Hope that helps!

Chris Angelico



More information about the Python-list mailing list