Anagram

Mats Kindahl matkin at iar.se
Wed Jan 23 10:44:43 EST 2002


nikolai.kirsebom at siemens.no (Nikolai Kirsebom) writes:

> Just for fun !!
> 
> Friend of mine who used to work with lisp (and is a bit interested in
> Python) asked me how compact I could write a program to evaluate the
> number of possible combinations a set of characters (string) can be
> written in - handling two identical characters as different
> characters.
> 
> Example:
> "ab" --> yields 2 ("ab", "ba")
> "abc" --> yields 6
> "aa" --> yields 2
> 
> My Python answer shown below.   Better solutions ?  Does anyone (here)
> know how this could be done in Perl ?
> -------------------
> import sys
> 
> def f(s,i):
>     if len(s) == 2 or i == 0: return min(i*len(s),2)
>     return f(s[1:], len(s)-1) + f((s[1:] + s[0]), i - 1)
> 
> if len(sys.argv) < 2:
>     print "Usage: python Script2.py words...."
>     sys.exit(0)
> for a in sys.argv[1:]:
>     print a, f(a, len(a))
> 
> ----------------
> 
> 

What's wrong with

    from operator import __mul__

    def f(s): return reduce(__mul__, range(1,len(s)+1), 1)

or in Perl

    sub f { return eval join('*', 1..length($_[0])) }

You don't have to generate all the words explicitly...

Best wishes,

-- 
Mats Kindahl, IAR Systems, Sweden

Any opinions expressed are my own, not my company's.



More information about the Python-list mailing list