help please
Steven Bethard
steven.bethard at gmail.com
Sun Feb 13 12:27:20 EST 2005
gargonx wrote:
> This works much better, aside from the fact that it does'nt work for
> the std dictionary. the letters used from here stay the same. that
> dictionary looks like this:
>
> std = {
> "A":"Z",
> "Z":"A",
> "B":"Y",
> "Y":"B",
> "C":"X",
> "X":"C",
> "E":"V",
> "V":"E",
> "H":"S",
> "S":"H",
> "M":"N",
> "N":"M"
> }
>
> what could be causing this?
>
> i did figure out that if you reverse the k,v you are able to get it but
> that doesn't turn up the results i need
>
> def proc(text):
> result = []
> for word in text:
> for k, v in replacements:
> word = word.replace(v,k) #here i reversed them
> result.append(word)
> return ''.join(result)
>
The problem is that if you run all the replacements in std, you first
translate As to Zs and then Zs to As. If you want to do each character
only once, you should probably write this as:
py> std = {
... "A":"Z",
... "Z":"A",
... "B":"Y",
... "Y":"B",
... "C":"X",
... "X":"C",
... "E":"V",
... "V":"E",
... "H":"S",
... "S":"H",
... "M":"N",
... "N":"M"}
py> ext = {"aa":"i"}
py> punc = {",":"!"}
py> replacements = {}
py> replacements.update(punc)
py> replacements.update(ext)
py> replacements.update(std)
py> def proc(text):
... result = []
... for char in text:
... result.append(replacements.get(char, char))
... return ''.join(result)
...
py> proc('ABCDEFG')
'ZYXDVFG'
Or alternatively:
py> def proc(text):
... return ''.join([replacements.get(c, c) for c in text])
...
py> proc('ABCDEFG')
'ZYXDVFG'
Note however, that this won't work for multi-character strings like you
had in 'ext' in your original example:
py> proc('ABCaaEFG')
'ZYXaaVFG'
But neither would your original code. Are the items in std always a
single character? Does ext always translate two characters to one?
Could you give us some more info on the task here?
Steve
More information about the Python-list
mailing list