Anagram
Joseph A Knapka
jknapka at earthlink.net
Thu Jan 24 12:54:44 EST 2002
Alex Martelli wrote:
>
> "Joseph A Knapka" <jknapka at earthlink.net> wrote in message
> news:3C4ED1A5.56CE7B60 at earthlink.net...
> ...
> > # 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]
>
> Not sure what you mean. "get the idx1-th element
> from list llis and remove it from the list too"
> is llis.pop(idx1); is that what you mean by
> "comprehend"?
As Mr Hogg rightly inferred, what annoys me is having
to first make a copy of "lis" and then remove the chosen
element. I wanted to something like:
llis = [some comprehension yielding lis-<the chosen index>]
but, I wanted it, y'know, comprehensible...
> > rest = pickana(llis,ana%fact(len(lis)-1))
> > return [which1] + rest
>
> Or, non-recursively...:
>
> def pickanagram(lis, anaind):
> result = []
> llis = lis[:]
> while llis:
> anaind, indx = divmod(anaind, len(llis))
> result.append(llis.pop(indx))
> return result
>
> I don't think the fact() calls in your pickana are
> correct -- I think you need a divmod(ana,len(lis))
> in your version too (or equivalently separate uses
> of operators / and % as you have, but divmod seems
> clearer to me in this case).
My version gives the correct results. We are counting
anagrams from opposite directions, more or less -
I'm chopping off high-order bits to choose list
indices, and you're chopping off low-order ones.
Your way is clearly better :-) It didn't occur to
me until I read your code that with this kind of
enumeration argument, it doesn't matter in which
direction you consume the index value.
> pickanagram seems nice & readable, but if squeezing
> functionality into fewer statements were the goal,
> something might be feasible. Usual disclaimers: I
> am *NOT* advocating the following as good, or even
> halfway sensible, Python programming, just playing
> with Joe's "challenge":-).
Yeah, right. Denial is the first sign...
> Basically, the body of pickanagram is CLOSE to a list
> comprehension (a single statement) plus the copy of
> lis (to make pickanagram nondestructive on its argument!);
> this suggests we need to check if we CAN indeed make it
> into a list-comprehension.
{insanity snipped}
Ow, Ow OW! That hurt my brain... and it felt goooood....
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