Anagram

Anton Vredegoor anton at vredegoor.doge.nl
Tue Feb 26 14:42:39 CET 2002


On Tue, 26 Feb 2002 08:42:37 +0000 (UTC), gaul at spam.utexas.edu (Andrew
Gaul) wrote:

>I'm suprised no one else has posted this (it's standard material in a
>university probability course).
>
>def uniq_perm(l):
>    ''' returns the number of unique permutations of a list.
>
>                      n!
>            ------------------------
>            n_1! * n_2! * ... * n_r!
>
>        computes the number of unique permutations of n objects, of which n_1
>        are alike, n_2 are alike, ... n_r are alike.  Take from _A First Course
>        in Probability_, 5th edition, Ross, pg 5.
>    '''
>
>    acc = fac(len(l))
>    l.sort()
>    i = 0
>    while i < len(l):
>        cnt = l.count(l[i])
>        acc /= fac(cnt)
>        i += cnt
>    return acc
>
>def fac(n):
>    ''' returns n! '''
>    assert n >= 0
>    if n == 0:
>        return 1
>    acc = 1
>    for i in range(1, n+1):
>        acc *= i
>    return acc
>
>
>Python 2.2 (#5, Jan 23 2002, 16:23:03)
>[GCC 3.0.3] on linux2
>Type "help", "copyright", "credits" or "license" for more information.
>>>> from perm import *
>>>> uniq_perm(list('pepper'))
>60
>>>> uniq_perm(list('aa'))
>1
>>>> uniq_perm(list('aba'))
>3

The OP confused the issue by naming the thread anagram while asking
for something else. It's only natural that after having answered the
OP's question the thread should go on according to its title. I wrote
a voluminous script to generate anagrams some time ago, and I am
looking for options to shorten the algorithm to a few lines of code as
has been done for the algorithm the OP asked a question about.

Its at:

http://home.hccnet.nl/a.vredegoor/multiperm/multiperm.html

or:

http://home.hccnet.nl/a.vredegoor/multiperm/multiperm.py




More information about the Python-list mailing list