A puzzle for Pythonistas
Alan James Salmoni
alan_salmoni at yahoo.com
Sat Feb 1 14:41:50 CET 2003
Thanks Padraig - really nice solution!
Padraig at Linux.ie wrote in message news:<3E3A76C3.1010503 at Linux.ie>...
> Alan James Salmoni wrote:
> > 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
> import sys
> def printList(alist):
> print ''.join(alist)
> def printUniqueCombinations(alist, numb, blist=):
> if not numb: return printList(blist)
> for i in range(len(alist)):
> printUniqueCombinations(alist[i+1:], numb-1, blist)
> if __name__ == '__main__':
> for i in range(len(list(k))):
> printUniqueCombinations(list(k), i+2)
More information about the Python-list