[Tutor] help

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sat, 15 Sep 2001 18:54:45 -0700 (PDT)


On Sat, 15 Sep 2001, Cameron Stoner wrote:

> What is wrong with this code?  When I ran this in the IDLE it brought
> up an unhashable type error.  I don't really understand why print
> dict[sep_letter] is a problem.  Would you tell me what would fix it
> please or what the flaw in the logic is.

Let's take a look:

> import string
> y = raw_input('prompt:')
> while y is not '':
>     sep_letter = (string.split(y[0][-1]))

If y is a string, then y[0] will be a single letter of that string, and
y[0][-1] --- that is, the last letter of y[0] --- will be that same
letter:

###
>>> name = 'cameron'
>>> name[0]
'c'
>>> name[0][-1]
'c'
>>> name[0][-1][-1]
'c'
###

It will be simpler to write:

    sep_letter = string.split(y[0])

But even then, I'm a little confused, since splitting a single letter is
probably not what you were planning.  This might be the cause for the
"unhashable type error" that you're running into.


Hmmm... Do you mean:

###
sep_letter = string.split(y)[0][-1]
###

instead?  This is more effective, since this says: "Split the string into
a list of smaller strings.  Pull out the first of those strings, and grab
at the last character of it."



>     while sep_letter is not '':
>         dict = 
> {'A':'1','B':'2','C':'3','D':'4','E':'5','F':'6','G':'7','H':'8','I':'9',
>                 
> 'J':'10','K':'11','L':'12','M':'13','N':'14','O':'15','P':'16',
>                 
> 'Q':'17','R':'18','S':'19','T':'20','U':'21','V':'22','W':'23','X':
>                 '24','Y':'24','Z':'25','':'','.':'~','?':'`'}
>         print dict[sep_letter]


It might be good to pull out the definition of the dictionary outside of
the while loop, just to emphasise the fact that its definition is not
really an important part of the looping.  Also, I think there's a small
bug, since both 'X' and 'Y' both map to '24'.

Here's a small function that might help:

###
def makeCodingDictionary():
    dict = {}
    for i in range(26):
         dict[chr(ord('A') + i)] = str(i+1)
    dict.update({'' : '',
                 '.' : '~',
                 '?' : '`'})
    return dict
###


Try making those corrections first, and tell us if it helps.  The first
fix should repair the bug you were running into.  Good luck!