On Mon, 24 Dec 2007 00:18:29 -0800, cf29 wrote: > On Dec 23, 2:04 pm, Steven D'Aprano <[EMAIL PROTECTED] > cybersource.com.au> wrote: >> def combinations(seq, n): >> if n == 0: >> yield [] >> else: >> for i in xrange(len(seq)): >> for cc in combinations(seq[i+1:], n-1): >> yield [seq[i]]+cc >> >> >>> for c in combinations(range(4), 3): >> ... print c >> Steven > > Thank you Steven, it works. I am so new to Python that I don't > understand fully how this function works to be able to adapt it to my > original problem. I wish I had a teacher :-)
(1) Read up on generators. Google is your friend. (2) Experiment in an interactive Python session. For example, look at this pair of functions: >>> def function(x, y, z): ... L = [] ... for i in (x, y, z): ... L.append(i) ... return L ... >>> def generator(x, y, z): ... for i in (x, y, z): ... yield i ... >>> print function(1, 2, 3) [1, 2, 3] >>> print generator(1, 2, 3) <generator object at 0xb7f7ee8c> >>> >>> >>> for i in function(1, 2, 3): ... print i ... 1 2 3 >>> for i in generator(1, 2, 3): ... print i ... 1 2 3 Now imagine, instead of returning three items, suppose you had a function that needed to return millions of items. A function using return would need to produce all of those items before it could make them available to you. A generator using yield can feed them to you one at a time, as soon as they're ready. (3) Read up on recursion, when a function calls itself. Hope that helps. -- Steven -- http://mail.python.org/mailman/listinfo/python-list