faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 5 people (40%) answered Yes
Recently 1 of 3 people (33%) answered Yes

Entry

Permutations

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 298, Python Snippet Support Team


"""
Packages: maths
"""
# module perm
# Permutatie-functies.
""" TO DO:
    * perm(x) only works with strings; it should work with all sequences.
    * Maybe I could define a better (faster?) algorithm to do this.
"""
_list = []
# p is de meest flexibele functie -- en ook de ingewikkeldste. Bij voorkeur
# andere functies in deze module aanroepen.
#
# n = aantal objecten in totaal (bijv. 52 kaarten)
# m = aantal in elke permutatie (bijv. 5 kaarten trekken)
# p2 = string met objecten (bijv. 'abc')
# p1 is in het begin altijd ''
#
def p(n,m,p1,p2,level):
    global _list
    if p1 == '': _list = []
    if level < m:
        nlevel = level + 1
        for i in range(len(p2)):
            p1n = p1 + p2[i]
            p2n = p2
            # delete(p2n, i, 1)
            p2n = p2n[:i] + p2n[i+1:]
            p(n, m, p1n, p2n, nlevel)
    else:
        _list = _list + [p1]
        # nperms = nperms + 1
    return _list
def permutations(str):
    l = len(str)
    return p(l, l, '', str, 0)
def perm(nr, str):
    return permutations(str)[nr]
def perm_nr(perm, str):
    perms = permutations(str)
    try:
        return perms.index(perm)
    except:
        return None
if __name__ == "__main__":
    print permutations('1')
    print permutations('12')
    print permutations('123')
    print perm_nr('321', '123')
    print permutations(['foo', 'bar', 'xyzzy'])
    print p(3,3,'','abc', 0)