A puzzle for Pythonistas

Levente Sandor sandorlevi at yahoo.com
Sat Feb 1 16:09:43 EST 2003


Pythonic? Elegant? Hmm...

L1 = [1, 2, 3, 4, 5]
L2 = []
for i in range(len(L1)+1):
    for j in range(i-1):
        L2.append(L1[j:i])
L2.sort(lambda a, b: len(a)>len(b) and 1 or len(a)<len(b) and -1 or 0)
print L2

----
levi

alan_salmoni at yahoo.com (Alan James Salmoni) wrote in message news:<b68f71a7.0301310459.31539d3c at posting.google.com>...
> Hi folks,
> 
> This is just a little puzzle to test your brains on - well, I should
> come clean really, so what I need to do is work out a way to get all
> the interactions from 2 or more variables for SalStat a small
> statistics package, but to be honest, I am rather stuck on this bit.
> 
> The problem is defined like this: I have a list of unique integers,
> and the list is of arbitrary length, though 2 elements is the minimum.
> Using each integer only once, what are the possible combinations of 2
> or more elements that can be derived from this list. I know how to
> work out how many combinations there are: ((2**len(list))-1-len(list))
> which is quite simple.
> 
> To illustrate:
> 
> If list = [1,2,3], then there are 4 possible combination: 1-2, 1-3,
> 2-3, and 1-2-3.
> If list = [1,2,3,4] then there are 11 possible combinations: 1-2, 1-3,
> 1-4, 2-3, 2-4, 3-4, 1-2-3, 1-2-4, 1-3-4, 2-3-4, and 1-2-3-4.
> 
> All my ideas so far rely on brute force, and I was wondering if anyone
> could think of an elegant and pythonic way of achieving the required
> result.
> 
> I have a nasty feeling that the code may be complex, so feel free to
> tell me to s0d off if you want! :)
> 
> Alan James Salmoni
> SalStat Statistics
> http://salstat.sunsite.dk




More information about the Python-list mailing list