Anagram

Joseph A Knapka jknapka at earthlink.net
Wed Jan 23 16:21:58 EST 2002


Nikolai Kirsebom wrote:
> 
> Just for fun !!

OK :) Here are a couple of ways to generate all the unique
anagrams of a list (which is now what you asked for,
but *is* fun!):

from __future__ import generators

# Generate them all and return 'em. Not recommended for
# > 4 elements or so.
def anas(lis):
    if len(lis) == 1:
        return [lis]
    results = []
    for item in lis:

        # This is annoying.
        llis = lis[:]
        llis.remove(item)

        for subana in anas(llis):
           results.append([item] + subana)
    return results

# Our old friend...
def fact(n):
    result = 1
    while n>0:
        result *= n
        n -= 1
    return result

# This one allows you to pick an anagram from anywhere
# in the sequence. <Ana> is the index of the anagram to
# pick from the possible anagrams of <lis>.
def pickana(lis,ana):
    if not lis:
        return []
    idx1 = int(ana/fact(len(lis)-1))
    which1 = lis[idx1]

    # Still annoying. Can I "comprehend" this somehow?
    llis = lis[:]
    del llis[idx1]

    rest = pickana(llis,ana%fact(len(lis)-1))
    return [which1] + rest

# This one generates them all as needed. This is
# really cool, I think I need to look into generators
# a bit more closely.
def anagen(lis):
    for i in range(fact(len(lis))):
	yield pickana(lis,i)

I'm sure some people here could do any of the above
with two-liners; I'd be interested to see those!

Cheers,

-- Joe
"I should like to close this book by sticking out any part of my neck
 which is not yet exposed, and making a few predictions about how the
 problem of quantum gravity will in the end be solved."
 --- Physicist Lee Smolin, "Three Roads to Quantum Gravity"



More information about the Python-list mailing list