Nested string substitutions

Lulu of the Lotus-Eaters mertz at gnosis.cx
Fri Dec 20 13:51:36 EST 2002


Mike Meyer <mwm at mired.org> wrote previously:
|There are two things wrong with your intuition here. First,
|string.replace generates a new string instead of updating the string
|it's invoked on in place.

True.  But the expression 'dct.__setitem__(...)' could, in principle,
occur in a map()/listcomp.  It might be that the returned list was a
list of None's, to be discarded.  I've done that sort of thing from time
to time.

|Second, it takes an indeterminate number of passes over each string to
|complete the replacement.

Nonetheless, I think Meyer is right.  Since a listcomp (or map(),
filter(), etc) cannot really act like a 'while', I probably just need to
unroll my loops.

|Figuring the right order out requires a topological sort

Yep... that's a lot of work, and I don't know how to do it at all off
the top of my head.

|Alternatives - well, we all know what you need if you want another
|way of spelling LOOP.

Damn! If only Python had macros, this would be so much easier. (*wink*)

|def expand(key, dct):
|    previous = ""
|    while previous != dct[key]:
|        previous = dct[key]
|        for old, new in dct.items():
|            dct[key] = dct[key].replace(old, new)
|    map(lambda x: expand(x, subs), subs.keys())

Yeah... this looks pretty nice.  I'll steal this version.  (but I
changed the spelling to avoid the builtin 'dict' name).

Btw. Sorry to Holger Krekel.  My example used spaces to separate all the
substitutable terms, and your solution relied on that.  But that isn't
the case in my actual problem (my description obviously wasn't quite
complete enough).  I could probably adapt your version to use
'.replace()', but the change doesn't jump out at me.

Yours, Lulu...

--
mertz@  | The specter of free information is haunting the `Net!  All the
gnosis  | powers of IP- and crypto-tyranny have entered into an unholy
.cx     | alliance...ideas have nothing to lose but their chains.  Unite
        | against "intellectual property" and anti-privacy regimes!
-------------------------------------------------------------------------





More information about the Python-list mailing list