[perl-python] combinatorics fun
David Eppstein
eppstein at ics.uci.edu
Thu Feb 10 18:35:56 EST 2005
In article <1108075884.250995.62520 at g14g2000cwa.googlegroups.com>,
"Xah Lee" <xah at xahlee.org> wrote:
> combo(n) returns a collection with elements of pairs that is all
> possible combinations of 2 things from n. For example, combo(4)
> returns {'3,4' => ['3',4],'1,2' => [1,2],'1,3' => [1,3],'1,4' =>
> [1,4],'2,3' => ['2',3],'2,4' => ['2',4]}; Hash form is returned
> instead of array for this program.
def combo(n):
return dict([('%d,%d'%(i,j),(i,j))
for j in range(n) for i in range(j)])
import pprint
pprint.pprint(combo(5))
output:
{'0,1': (0, 1),
'0,2': (0, 2),
'0,3': (0, 3),
'0,4': (0, 4),
'1,2': (1, 2),
'1,3': (1, 3),
'1,4': (1, 4),
'2,3': (2, 3),
'2,4': (2, 4),
'3,4': (3, 4)}
Note I'm using 0-based indexing, use range(1,n+1) and range(1,j+1)
instead if you really need it to be 1-based.
Also I'm using Python 2.3, I think in 2.4 you can take out the square
brackets and it would still work.
--
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list