[perl-python] combinatorics fun

Xah Lee xah at xahlee.org
Fri Feb 11 01:38:20 EST 2005


David Eppstein's code is very nice.

Here's the python version of the perl code:

©# -*- coding: utf-8 -*-
©# Python
©
©def combo (n):
©    '''returns all possible (unordered) pairs out of n numbers 1 to
n.
©
©    Returns a dictionary. The keys are of the form "n,m",
©    and their values are tuples. e.g. combo(4) returns
©    {'3,4': (3, 4), '1,4': (1, 4), '1,2': (1, 2),
©    '1,3': (1, 3), '2,4': (2, 4), '2,3': (2, 3)}'''
©    result={}
©    for j in range(1,n):
©        for i in range(1,n+1):
©            m = ((i+j)-1) % n + 1
©            if (i < m):
©                result["%d,%d"%(i,m)]=(i,m)
©    return result
©
©print combo(4)

So sweet.

 Xah
 xah at xahlee.org
 http://xahlee.org/PageTwo_dir/more.html




More information about the Python-list mailing list