1
def endcode(msg,secret_d):
    for ch in msg:
        for key,value in secret_d:
             if ch == key:
                 msg[ch] = value
    return msg
encode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'}) 

This is my code. What I am trying to do here is for every characters in a string msg, the function should search in the dictionary and replace it with the mapping string if the character ch is a key in the dictionary secret_d.

If ch is not a key in secret_d than keep it unchanged.

For the example, the final result is should be 'C4N YOU R34D 7H15'

timgeb
  • 76,762
  • 20
  • 123
  • 145
brian012
  • 193
  • 1
  • 2
  • 12

2 Answers2

0

Your function name is endcode but you are calling encode.

But more important, I'll give you a hint to what's going on. This isn't going to totally work, but it's going to get you back on track.

def endcode(msg,secret_d):
    newstr=""
    for ch in msg:
        for key,value in secret_d.iteritems():
            if ch == key:
                newstr=newstr+value
    print(msg)
endcode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'}) 

But if you want a complete answer, here is mine.

rb612
  • 5,280
  • 3
  • 30
  • 68
0

A few issues:

  • As rb612 pointed out, there's a typo in your function definition ("endcode")
  • you are doing nothing with the return value of your function after calling it
  • msg[ch] is trying to assign items in a string, but that's not possible, strings are immutable. You'll have to build a new string. You cannot "update" it.
  • in order to iterate over (key, value) pairs of a dictionary d, you must iterate over d.items(). Iterating over d will iterate over the keys only.

That being said, here's my suggestion how to write this:

>>> def encode(msg, replacers):
...     return ''.join([replacers.get(c, c) for c in msg])
... 
>>> result = encode('CAN YOU READ THIS',{'A':'4','E':'3','T':'7','I':'1','S':'5'})
>>> result
'C4N YOU R34D 7H15'

Things to note:

  • dict.get can be called with a fallback value as the second argument. I'm telling it to just return the current character if it cannot be found within the dictionary.
  • I'm using a list comprehension as the argument for str.join instead of a generator expression for performance reasons, here's an excellent explanation.
Community
  • 1
  • 1
timgeb
  • 76,762
  • 20
  • 123
  • 145
  • This is definitely a good answer. Mine (now edited) will do the same but overall not nearly as clean and compact. – rb612 Apr 01 '16 at 05:26