I'm very new to Python and am working my way through the "Learn Python The Hard Way" web tutorial. But I've come to a halt as I have an issue with passing a single string. I'm able to pass a list OK...
Exercise 48 is getting us to reverse engineer the code from a unit test. The unit test is:
def test_directions():
assert_equal(Lexicon.scan("north"), [('direction', 'north')])
My code looks like this:
class Lexicon:
def __init__(self):
self.directions = ['north','south','east','west','down','up','left','right','back']
self.verbs = ['go','stop','kill','eat']
self.stops = ['the','in','of','from','at','it']
self.nouns = ['door','bear','princess','cabinet']
def scan(self, words):
result = []
for i in words:
if i in self.directions:
result.append( ('direction', i) )
elif i in self.verbs:
result.append( ('verb', i) )
elif i in self.stops:
result.append( ('stop', i) )
elif i in self.nouns:
result.append( ('noun', i) )
else:
try:
result.append( ('number', int(i)) )
except ValueError:
result.append( ('error', i) )
return result
Running the code from the python prompt gives me the following results:
>>> from lexicon import Lexicon
>>> test = Lexicon()
>>> test.directions
['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
>>> words = ['south']
>>> test.scan(words)
[('direction', 'south')]
>>>
>>> test.scan("north")
[('error', 'n'), ('error', 'o'), ('error', 'r'), ('error', 't'), ('error', 'h')]
>>>
I'd be very grateful if someone could point out why lists are being treated differently to the single string? And also how I can re-write my code so that both are treated the same way?
Thanks in advance, Nigel.
unittestin that exercise also shows a single string argument of multiple words separated by spaces - you will want to account for that in your method.